public class CountDigitOne {
public static void main(String[] args) {
int a = 27;
int i = countDigitOne(a);
System.out.println(i);
}
public static int countDigitOne(int n) {
if (n < 1) {
return 0;
}
int res = 0;
long i = 1;
while (n >= i) {
res += (n / i + 8) / 10 * i + ((n / i) % 10 == 1 ? (n % i + 1) : 0);
i *= 10;
}
return res;
}
}
解法2
public class CountDigitOne2 {
public static void main(String[] args) {
int a = 27;
int i = countDigitOne(a);
System.out.println(i);
}
public static int countDigitOne(int n) {
if (n <= 0) {
return 0;
}
String stringN = n + "";
int ans = 0;
while (!stringN.isEmpty()) {
int tempLen = stringN.length();
String firstChar = stringN.charAt(0) + "";
if (Integer.parseInt(firstChar) >= 2) {
ans += 1 * Math.pow(10, tempLen - 1);
} else if (firstChar.equals("1")) {
if ("".equals(stringN.substring(1, tempLen))) {
ans += 1;
} else if (!"".equals(stringN.substring(1, tempLen))) {
ans += Integer.parseInt(stringN.substring(1, tempLen)) + 1;
}
}
if (tempLen > 1) {
ans += Integer.parseInt(firstChar) * (tempLen - 1) * Math.pow(10, tempLen - 2);
}
stringN = stringN.substring(1);
}
return ans;
}
}