/**
* 求1 的個數
*
* 對于 abcdef 幾個數字,我們求小于abcdef 的所有資料中包含的1的個數,如果 P(13) = 6 對于分析,我們能得出以下結論 如:對于 c
* 位上的數有以下三種情況 1. c=0 p= c 高位的數字 * C的位數 2. c=1 p = c 高位的數字*c的位數 + c 低位的數 3. c>1
* p = (c高位的數字+1) *c 位數
*/
public class TheNumberOfOne {
static void execute(int n) {
int factor = 1, high, low;
int count = 0;
while (n / factor != 0) { // 表示還有高位
int pos = n / factor % 10; // 目前位值
high = n / (factor * 10);
low = n - (n / factor) * factor;// 高位與低位值
switch (pos) {
case 0:
count += high * factor;
break;
case 1:
count += high * factor + low + 1;
break;
default:
count += (high + 1) * factor;
break;
}
factor *= 10;
}
System.out.println(count);
}
public static void main(String args[]) {
int n = 123;
execute(n);
}
}