题解 | #[NOIP2013]记数问题#

[NOIP2013]记数问题

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

import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int x = sc.nextInt();
        // 方法一:使用StringBuilder接收 1~n,遍历sb,检查每个字符和目标是否相等
        // 注意整型、字符之间格式的转换
//         StringBuilder sb = new StringBuilder();
//         int count = 0;
//         for(int i=1; i<=n; i++){
//             sb.append(i);
//         }
//         for(int i=0; i<sb.length(); i++){
//             if(sb.charAt(i) == '0' + x){
//                 count++;
//             }
//         }

        // 方法二:检查每个整数的各个数位,是否和目标x相等。
        int count = 0;
        int temp = 0;
        for(int i=1; i<=n; i++){
            temp = i;
            while(temp > 0){
                if(temp % 10 == x){
                    count++;
                }
                temp /= 10;
            }
        }
        System.out.println(count);
    }
}
全部评论

相关推荐

求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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