标签:
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.
分析:
假设给定数字327,那么个位上最多会出现多少次1呢?是不是应该有33个?从001, 011,021,031,一直到321呢?答案是对的。
那么十位上有多少个一呢,是不是有(3+1)*10 = 40个呢?怎么算的呢?011,012, 013,。。。 111, 112, 113,。。。 211,212,213.。。311,312,313,。。。319。
那么百位上有多少1呢,是不是有1*100呢?答案也是正确的。从100 到199.
这里有特殊情况,比如,317,十位上有多少个1呢,答案是3 * 10 + 18。
对于123,那么对于百位上有多少个1呢,是不是24个?从100 到123.
对于302,十位上有多少个1呢?是不是就是30个呢? 010-019, 110-119, 210-219.
1 public class Solution { 2 public int countDigitOne(int n) { 3 if (n < 0) return 0; 4 int power = 0; 5 int res = 0; 6 String num = String.valueOf(n); 7 8 for (int i = num.length() - 1; i >= 0; i--) { 9 int v = num.charAt(i) - ‘0‘; 10 int beforeI = 0, afterI = 0; 11 12 if (i != 0) { 13 beforeI = Integer.parseInt(num.substring(0, i)); 14 } 15 16 if (i != num.length() - 1) { 17 afterI = Integer.parseInt(num.substring(i + 1)); 18 } 19 20 if (v == 0) { 21 res += beforeI * (int) (Math.pow(10, power)); 22 } else if (v == 1) { 23 if (i == num.length() - 1) { 24 res += (beforeI + 1) * (int) (Math.pow(10, power)); 25 } else if (i == 0) { 26 res += (afterI + 1); 27 } else { 28 res += beforeI * (int) (Math.pow(10, power)); 29 res += (afterI + 1); 30 } 31 } else if (v >= 2) { 32 res += (beforeI + 1) * (int) (Math.pow(10, power)); 33 } 34 power++; 35 } 36 return res; 37 } 38 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5745856.html