Title:
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.
Code:
Class Solution {public: int countdigitone (int n) { int ones = 0; For (long long m = 1; M <= n; m *=) { ones + = (n/m + 8)/ten * m + (n/m% = = 1) * (n% m + 1); } return ones;} ;
Tips:
We give the code first, and we analyze it. The body logic of the code is parsed from the lowest bit to the left.
Because for each person, there are several situations that need to be discussed separately, namely:
- The bit is greater than 1: if it is greater than 1, then the number of times that the bit appears 1 is (n/m + 8)/ten * M
- The bit is 0: if the bit is 0, then in the above equation (n/m + 8)/ten * M , +8 does not produce a carry, so the correct answer can still be obtained
- This bit is 1: If the bit is 1, then although the above formula will still not carry, but we also need to add the number of lower part, so there will be:(n/m% = = 1) * (n% m + 1)
"Leetcode" 233. Number of Digit One