OpenJudge:40. 数1的个数
给定一个十进制正整数n,写下从1到n的所有整数,然后数一下其中出现的数字“1”的个数。
例如当n=2时,写下1,2。这样只出现了1个“1”;当n=12时,写下1,2,3,4,5,6,7,8,9,10,11,12。这样出现了5个“1”。
输入 正整数n。1 <= n <= 10000。 输出 一个正整数,即“1”的个数。 样例输入 12 样例输出 5二、暴力法 算法
将 i从 11遍历到 n:将每个i中1’ 的个数累加到变量 count返回 count java代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
Main count = new Main();
System.out.println(count.countDigitOne(n));
}
public int countDigitOne(int n) {
int count = 0;
int temp = 1;
for (int i = 1; i <= n; i++) {
temp = i;
while (temp != 0) {
count += (temp % 10 == 1) ? 1 : 0;
temp = temp / 10; //数据类型强制转换
}
}
return count;
}
}
三、逐位遍历
思路:将所有数字拼接起来,然后再逐位遍历


