问题描述
输入正整数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); } } }
原文:https://www.cnblogs.com/BLACKJT/p/12202974.html