Leetcode 233: Number of Digit One, leetcodedigit
Number of Digit OneTotal Accepted:307Total Submissions:1853
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.
[Idea]
Reference: https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python
Intuitive: each 10 digits, each with 1 bits, every 100 bits, 10 10 digits with 1 bits, every 1000 bits, and 100 bits with 1 bits. create a loop and calculate the total number (one digit, ten digits, and hundreds of digits) of a single bit ).
Example:
Taking the last hundred bits as an example: assume that the last hundred bits is 0, 1, and> = 2:
Case 1: n = 3141092, a = 31410, B = 92. The number of 1 in a hundred bits should be 3141*100 times.
Case 2: n = 3141192, a = 31411, B = 92. The number of 1 in a hundred bits should be 3141*100 + (92 + 1) times.
Case 3: n = 3141592, a = 31415, B = 92. Calculate the number of 1 in a hundred bits (3141 + 1) x 100 times.
The above three cases can be summarized using a formula:
(a + 8) / 10 * m + (a % 10 == 1) * (b + 1);
[CODE]
public class Solution { public int countDigitOne(int n) { int ones = 0; for (long m = 1; m <= n; m *= 10) { long a = n/m, b = n%m; ones += (a + 8) / 10 * m; if(a % 10 == 1) ones += b + 1; } return ones; }}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.