java 给出一个整数N,输出10个数字:(1--N之间含有多少0,1,2,3,4,5,6,7,8,9)

RT,想了挺久不知道怎么弄,感觉要靠数字长度来算,但是又不知道怎么做


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author yugi111 <br>
 *  compute how many 0-9
 */
public class ComputeHowManyNums
{
public static void main( String[] args )
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputTip = "please input N numbers:";
System.out.println(inputTip);
String N = "0";
try
{
while(!( N = (br.readLine()).trim() ).matches("^[1-9]\\d+|\\d$"))
{
System.out.println(inputTip);
}
}
catch(IOException e)
{
e.printStackTrace();
}

// from 1 to N
String result = " ";
for( int i = 1; i <= Integer.parseInt(N); i++ )
{
result += i;
}
result += " ";

System.out.println("result is :" + result);

// compute 0-9
for( int i = 0; i < 10; i++ )
{
System.out.println(i + " : " + (result.split(String.valueOf(i)).length - 1));
}
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-03-09
循环1到N,使用Map来存储(或者直接用数组)次数啊。
要想提高效率的话,首先求出N-N%10的值,设为S,然后把S/10。从1循环这个数记录出现数字的次数,记得每次循环时所有数的次数都要额外+1
个人想法,不知道有没有更好的
第2个回答  2014-03-09
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数:");
int n = sc.nextInt();
// 创建数组,存放0-9每个数字有多少个
int[] num = new int[10];
// 循环,对每个整数求其中包含的0-9个数,然后加和
for (int i = 0; i <= n; i++) {
int[] nn = getNum(i);
for (int j = 0; j < num.length; j++) {
num[j] += nn[j];
}
}
// 输出结果
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] + "  ");
}
}

// 对一个整数,求出其中包含0-9个数,返回数组
private static int[] getNum(Integer n) {
int[] nn = new int[10];
char[] chars = n.toString().toCharArray();
for (char c : chars) {
nn[Integer.parseInt(c + "")]++;
}
return nn;
}
}

相似回答