Wins the offer - the number of integers 1 appeared 45

Title Description

Calculated the number of integer of 1 to 13 1 arise, and calculates the number of times an integer from 100 to 1300 in 1 occur? To this end he especially counted about 1 to 13 contains the digits 1 has 1,10,11,12,13 therefore appear a total of six times, but for the problem behind him Meizhe. ACMer hope you will help him, and the problem is more generalized, the number of non-negative integer in the range 1 appears (the number of occurrences from 1 to n. 1) can quickly find any.
 
Solution:
  find the law questions:
 1 class Solution {
 2 public:
 3     int NumberOf1Between1AndN_Solution(int n)
 4     {
 5         if (n <= 0)return 0;
 6         int  left = 0, right = 0, a = 1, now = 1, ans = 0;
 7         while (n / a) {
 8             left = n / (a * 10), now = n / a % 10, right = n % a;
 9             if (now == 0) ans += left * a;
10             else if (now == 1) ans += left * a + right + 1;
11             else ans += (left + 1) * a; 
12             a = a * 10;
13         }
14         return ans;
15     }
16 };

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/11695063.html