Title Description
1 class Solution { 2 private: 3 int NumberOf1(unsigned int n) { 4 int cnt = 0; 5 while (n) { 6 if (n % 10 == 1) { 7 cnt++; 8 } 9 n /= 10; 10 } 11 return cnt; 12 } 13 public: 14 int NumberOf1Between1AndN_Solution(int n) 15 { 16 int number = 0; 17 for (unsigned int i = 1; i <= n; ++i) { 18 number += NumberOf1(i); 19 } 20 return number; 21 } 22 };
Ideas 2: Using mathematical induction, directly n the analysis, summarized the law
For example, n = abcde five digits, we analyze one hundred of c, mainly in the following three conditions:
1) When c == 0, for example 13013, this case is one hundred 1 appears: 00 100 to 00 199, 01 100 ~ 01 199, ......, 100 - 11 11 - 12 199 Total 1300 199,12100, obviously, this decision by the high numbers, and by the impact of the current number of bits, the result is :( higher digits) multiplied by (current median);
2) when c == 1, such as 13113, then one hundred sure 1 appears comprising c = 0, also need to consider the case where that is low: a total of 00 100 114 ~ 00 113, the result is a digital high :() multiplying (current median) + (lower digit) + 1;
3) when c> = 2, when, for example 13213, this case is one hundred 1 appears: 00 100 to 00 199, 01 100 ~ 01 199, ......, 11 ~ 11 100 ~ 12 100 199,12 199,13100 13199 ~, co-1400 a, this is determined only by the high numbers, the result is higher digits :( +1) multiplied by the current median.
1 class Solution { 2 public: 3 int NumberOf1Between1AndN_Solution(int n) 4 { 5 long long lower, higher, cur; 6 long long cnt = 0; 7 long long factor = 1; 8 for (int i = 1; i <= n; i *= 10) { 9 lower = n % i; 10 higher = n / (i * 10); 11 cur = (n / i) % 10; 12 if (cur == 0) { 13 cnt += higher * i; 14 } else if (cur == 1) { 15 cnt += higher * i + lower + 1; 16 } else { 17 cnt += (higher + 1) * i; 18 } 19 } 20 return cnt; 21 } 22 };
Thinking three: Digital dp (under study)
1 class Solution { 2 public: 3 int dp[30][30]; 4 int digit[30]; 5 6 int dfs(int l, int cnt, bool flag) { 7 if (l == 0) return cnt; 8 if (!flag && ~dp[l][cnt]) return dp[l][cnt]; 9 int pos = flag ? digit[l] : 9; 10 int ret = 0; 11 for (int i = 0; i <= pos; i++) { 12 ret += dfs(l - 1, cnt + (i == 1), flag && (pos ==i)); 13 } 14 if (!flag) dp[l][cnt] = ret; 15 return ret; 16 } 17 18 int countDigitOne(int n) { 19 memset(dp, -1, sizeof(dp)); 20 int pos = 0; 21 while(n) { 22 digit[++pos] = n % 10; 23 n /= 10; 24 } 25 return dfs(pos, 0, true); 26 } 27 };