The number of occurrences of 1 in JZ31 integer

Title description
Find the number of occurrences of 1 in the integer of 1 13, and calculate the number of occurrences of 1 in the integer of 100 1300? For this reason, he specially counted the numbers containing 1 from 1 to 13. There are 1, 10, 11, 12, and 13, so there are 6 times in total, but he has nothing to do with the following questions. ACMer hopes that you can help him and make the problem more generalized. You can quickly find the number of occurrences of 1 in any non-negative integer interval (the number of occurrences of 1 from 1 to n).

Solution: The most direct method is to traverse the numbers from 1 to n, and check the occurrence of 1 in turn. The implementation procedure is as follows:

class Solution {
    
    
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
    
    
        int cnt = 0;
        int m = 0;
        
        for(int i = 1;i <= n;i++)
        {
    
    
            for(int j = i; j > 0; j /= 10)
            {
    
    
                if(j % 10 == 1)
                    cnt++;
            }
        }
        
        return cnt;
    }
};

Guess you like

Origin blog.csdn.net/pikaqiu_n95/article/details/110100668