首页 文章

数字出现在整数[Java]中的时间

提问于
浏览
-2

写一个Java函数计数位数(int num);其中num是正整数 . 该函数计算每个数字0..9出现在num中的次数,并打印结果(参见下面的示例) . 示例:调用计数位数(347213);将打印以下内容:“数字0在347213中显示0次....(与1,2,3相同)..不允许辅助/递归,仅迭代 .

import java.Math.;

public int count-digits (int num){
int count = 0;
String numF = string.valueOf(num);
  // We get the number of digits by logs.
  for(int j=0; j <= 9; j++){ //loop for each digits
    for(int i=0; i < Math.floor(Math.log10(num)); i++){ //this loops checks each no.
      if(numF.charAt(j).equals(i)){
         count++;
      }
      return count;
      count=0;
    }      
  }
}

两个问题:

(1)如何将弦返回到它?

(2)这有用吗?有更好的解决方案吗?

1 回答

  • 0
    public void countDigits(int num) {      
        int count=0;
        String numF = String.valueOf(num);
    
        for (int j = 0; j <= 9; j++) {
            count=0;
            for (i = 0; i <numF.length(); i++) {
                char c = numF.charAt(i);
                String number=String.valueOf(j);
                if (c == number.charAt(0)) {
                    count++;
                }
            }
            System.out.println("The number " + j + " appaeared " + count + " times in 347213");
    
        }
    }
    

    对于这种方法,你得到这样的输出

    The number 0 appaeared 0 times in 347213
    The number 1 appaeared 1 times in 347213
    The number 2 appaeared 1 times in 347213
    The number 3 appaeared 2 times in 347213
    The number 4 appaeared 1 times in 347213
    The number 5 appaeared 0 times in 347213
    The number 6 appaeared 0 times in 347213
    The number 7 appaeared 1 times in 347213
    The number 8 appaeared 0 times in 347213
    The number 9 appaeared 0 times in 347213
    

    你不能将字符与 equals 进行比较 . 因此你需要有2个字符可以与 == 比较,因为你不能将 int 转换为 char 你得到一个长度为1的字符串并取第一个字符 . 我希望我能找到你想要的东西 .

相关问题