题目:
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
给定一个整数n,计算所有小于等于n的非负整数中数字1出现的次数。
例如:
给定 n = 13,
返回6, 因为数字1在下面的数字中出现:1, 10, 11, 12, 13(共6次)。
解法一:
package com.liangdianshui;
import java.util.Scanner;
public class algorithm1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long value = scanner.nextLong();
long startTime = System.currentTimeMillis();
String valueOf = String.valueOf(CountOne(value));
long endTime = System.currentTimeMillis();
long time = endTime - startTime;
System.out.println("1的数目:" + valueOf + "\n用时:" + time+"ms");
}
public static long CountOne(long n) {
long count = 0, i = 0, j = 1;
for (i = 0; i <=n; i++) {
j = i;
while (j != 0) {
if (j % 10 == 1) {
count++;
}
j /= 10;
}
}
return count;
}
}
解法二:
package com.liangdianshui;
import java.util.Scanner;
public class algorithm2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long value = scanner.nextLong();
long startTime = System.currentTimeMillis();
String valueOf = String.valueOf(CountOne(value));
long endTime = System.currentTimeMillis();
long time = endTime - startTime;
System.out.println("1的数目:" + valueOf + "\n用时:" + time+"ms");
}
public static long CountOne(long n) {
long count = 0;
if (n == 0)
count = 0;
else if (n > 1 && n < 10)
count = 1;
else {
long highest = n;// 最高位的数字
int bit = 0;
while (highest >= 10) {
highest = highest / 10;
bit++;
}
int weight = (int) Math.pow(10, bit);// 最高位的权重,即最高位一个1代表的大小
if (highest == 1) {
count = CountOne(weight - 1) + CountOne(n - weight) + n
- weight + 1;
} else {
count = highest * CountOne(weight - 1)
+ CountOne(n - highest * weight) + weight;
}
}
return count;
}
}
解法三:
package com.liangdianshui;
import java.util.Scanner;
public class algorithm3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long value = scanner.nextLong();
long startTime = System.currentTimeMillis();
String valueOf = String.valueOf(CountOne(value));
long endTime = System.currentTimeMillis();
long time = endTime - startTime;
System.out.println("1的数目:" + valueOf + "\n用时:" + time+"ms");
}
public static long CountOne(long n) {
long count = 0;
long i = 1;
long current = 0, after = 0, before = 0;
while ((n / i) != 0) {
current = (n / i) % 10;
before = n / (i * 10);
after = n - (n / i) * i;
if (current > 1)
count = count + (before + 1) * i;
else if (current == 0)
count = count + before * i;
else if (current == 1)
count = count + before * i + after + 1;
i = i * 10;
}
return count;
}
}