Topics
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.
Thinking of solving problems
Topic Understanding :
The title means that given a number n, the number of occurrences in the interval of [0, N] is calculated 1.
Specific Ideas :
If you are asked a similar question during the interview process, be sure not to worry because it is a regular problem. The best way to do this is to write an almost large number on the white paper, and then analyze how the number of occurrences of each digit 1 is calculated.
Take 24071 as an example, if we want to calculate the number of 1 occurrences of the Hundred, the specific idea is as follows:
- Get the top of the hundred to 24, get the lowest of the hundred to 71, the current hundred number is 0.
- From the high-level analysis, the number of hundred occurrences are: 00100~00190,01100~01190,02100~02190,..., 23100~23190. A total of (24*100) 1 appeared.
This is the case of hundreds of 0, if the Hundred is 1, that in addition to the above (24*100) 1, also includes: 24100~24171, a total of (71 + 1) 1, that is, total: 24 * 100 + 71 + 1.
If the hundred is greater than 1 for example 6, that in addition to the first (24*100) 1, also includes: 24100~24199, a total of 100 1, that is, the total: (24 + 1) *100.
Summarize the law
In fact, through the above analysis, we can sum up a rule as follows.
The number of occurrences of the I-bit 1 is required, and the high number of I is highn, the low number is Lown, the number of the current position I is cdigit, then the number of occurrences of the current I-bit 1 is divided into three cases:
- Cdigit = = 0, Count = Highn * factor.
- Cdigit = = 1, Count = Highn * factor + Lown + 1.
- Cdigit > 1, Count = (Highn + 1) * factor.
Where factor is the current product factor, for example, the factor of the Hundred is 100, and the 10-bit product factor is 10.
With the rule, the code can be written according to the law.
AC Code
Public class numberofdigitone { Public int Countdigitone(intN) {intCount =0;LongFactor =1;LongCdigit =0;LongHighn =0;intLown =0; while(N/factor >0) {cdigit = (n% (factor *Ten))/factor; Highn = N/(Factor *Ten);if(Cdigit = =0) {count + = Highn * factor; }Else if(Cdigit = =1) {count + = Highn * factor + Lown +1; }Else{count + = (Highn +1) * factor; } Lown + = Cdigit * factor; Factor *=Ten; }returnCount } Public Static void Main(string[] args) {intn =1410065408; Numberofdigitone Ndo =NewNumberofdigitone ();intCount = Ndo.countdigitone (n); System.out.println (count); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Number of Digit One, problem solving report