蓝桥杯试题:1的个数

问题描述
  输入正整数n,判断从1到n之中,数字1一共要出现几次。例如1123这个数,则出现了两次1。例如15,那么从1到15之中,一共出现了8个1。
输入格式
  一个正整数n
输出格式
  一个整数,表示1出现的资料
样例输入
15
样例输出
8
数据规模和约定
  n不超过30000

思路:

/*
* 1.获取一个数,将数转成字符串,
* 2.将这个数循环,如果有一,则count++;
* 3.在判断下一个是否有一
* 4.最后输出count
*/

import java.util.Scanner;
public class Main {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int number=sc.nextInt();
        int count=0;
        
        if(number<30000) {
            for(int i=1;i<number+1;i++) {
                String str=String.valueOf(i);
                for(int j=0;j<str.length();j++) {
                    if(str.charAt(j)=='1') {
                        count++;
                    }
                }
            }
            System.out.println(count);
        }
    }

}
posted @ 2020-01-16 19:52  是馄饨呀  阅读(333)  评论(0编辑  收藏  举报