# Solution and description.

• for example input is '2123'

.

from 0 to 2120 number of 1 is 212 * 1 in 1 unit

from 0 to 2100 number of 1 is 21 * 10 in 10 unit

from 0 to 2000 number of 1 is 2 * 100 in 100 unit

and...

from 0 to 3 number of 1 is 1 * 1 in 1 unit

from 0 to 23 number of 1 is 1 * 10 in 10 unit

from 0 to 123 number of 1 is not 1 * 100 but 23 + 1 in 100 unit

from 0 to 2123 number of 1 is 1 * 1000 in 1000 unit

``````public class Solution {
public int countDigitOne(int n) {
if (n <= 0)
return 0;
int rst = 0;
int unitCnt = 1;
int length = String.valueOf(n).length();
while (unitCnt <= length) {
int upperUnit = (int)Math.pow(10, unitCnt);
int currentUnit = (int)Math.pow(10, unitCnt - 1);
if (unitCnt != length)
rst += (int)((int)(n / upperUnit) * currentUnit);

int r = (int)(n % upperUnit);
if ((int)(r / currentUnit) == 1) {
rst += r % (int)currentUnit + 1;
} else if ((int)(r / currentUnit) > 1) {
rst += (int)currentUnit;
}
unitCnt++;
}
return rst;

}
``````

}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.