题解 | 记数问题

记数问题

https://www.nowcoder.com/practice/28b2d9f2bf2c48de94a1297ed90e1732

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int x = in.nextInt();
        int count = 0;
        //法1:逐位判断
        /*int temp = 0;
        for(int i = 0; i <= n; i++){
            temp = i;
            while(temp > 0){
                if(temp % 10 == x){
                    count++;
                }
                temp /= 10;
            }
        }*/
        //法2:字符串
        char num = (char)(x + '0');
        for(int i = 1; i <= n; i++){
            String result = String.valueOf(i);
            for(int j = 0; j < result.length(); j++){
                if(result.charAt(j) == num){
                    count++;
                }
            }
        }
        System.out.print(count); 
    }
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务