Java算法编程题:题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。
Java算法编程题:
题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。
例如输入12,从1到12这些整数中包含1的数字有1,10,11和12,1一共出现了5次。
解法:
// Java代码
public class NumberOf1 {
public static int numberOf1(int n) {
int count = 0;
while (n != 0) {
if (n % 10 == 1) {
count++;
}
n = n / 10;
}
return count;
}
public static int countNumberOf1(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
count += numberOf1(i);
}
return count;
}
public static void main(String[] args) {
System.out.println(countNumberOf1(12));
}
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(3条)