233.number-of-digit-one.go 593 B

12345678910111213141516
  1. func countDigitOne(n int) (ones int) {
  2. // Every 1000 has 100 ones at hundreds digit, every 100 has 10 ones at tens digit, ...
  3. // Assume the base of curr digit (like 1000) is m, then a = n / m, b = n % m,
  4. // If curr digit is 0, the ones of curr dight is a / 10 * base;
  5. // curr digit is 1, the ones is a / 10 * base + (b + 1);
  6. // curr digit is 2~9, the ones is (a / 10 + 1) * base.
  7. // So, the ones of curr digit is (a + 8) / 10 * base + (a % 10 == 1) * (b + 1)
  8. for m := 1; m <= n; m *= 10 {
  9. a, b := n/m, n%m
  10. ones += (a + 8) / 10 * m
  11. if a%10 == 1 {
  12. ones += b + 1
  13. }
  14. }
  15. return
  16. }