题目

计算数字k在0到n中的出现的次数,k可能是0~9的一个值

样例

例如n=12,k=1,在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],我们发现1出现了5次 (1, 10, 11, 12)

解题

暴力,余数是否等于k。

class Solution {
    /*
     * param k : As description.
     * param n : As description.
     * return: An integer denote the count of digit k in 1..n
     */
    public int digitCounts(int k, int n) {
        // write your code here
         int count = 0;
         for(int i = 0 ;i <= n ; i ++){
             int m = i;
             if(m==0&&k==0){
                 count+=1;
             }else{
                 while(m!=0){
                     if(m%10==k){
                         count++;
                     }
                     m=m/10;
                 }
             }
             
             
         }
         return count;
    }
};
Java Code

相关文章:

  • 2022-12-23
  • 2021-07-01
  • 2021-07-03
  • 2022-12-23
  • 2022-12-23
  • 2022-03-08
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
  • 2021-06-23
  • 2022-12-23
  • 2021-09-10
  • 2021-06-02
相关资源
相似解决方案