For an interview question, 1 ~ Number of times 1 appears in n

Source: Internet
Author: User

This afternoon, I was bored in my entrepreneurship education class. I thought of a Microsoft interview question ~ Number of times 1 appears in N


For example, if n = 11, then 1 appears four times: 1 10 11.


I have been thinking about this issue for a while and launched a fast solution (complexity lg (N )...

Idea: first determine the number of single-digit 1, and then count the number of ten-digit 1.

The procedure for setting n = 497 is as follows:


One digit:


Because the "49" in 497 is obtained by the bitwise carry, it is not difficult to come up with a single digit that has a forward of 49 digits. Each carry digit has a 1, therefore, the number of a single digit 1 is equal to 490/10 + the remaining '7' contains 1 digit, totaling 490/10 + 1 = 50


10 to 1:


It is not hard to think that the numbers above 497 are all generated by the decimal places. Therefore, the decimal places are 400/100 = four times, and each decimal place contains 10 digits of a single digit, therefore, the number of "1" in 10 of 497 is 400/100x10 + 10 = 50.


Hundred bits and 1 bits: Because the hundred bits are the highest bits and the hundred bits are greater than 1, the hundred bits contain 1 bits and 100 bits...


When N = 497 is accumulated, the total number of 1 instances is 50 + 50 + 100 = 200 .....


Based on the above idea, we can get an algorithm with the complexity of lg (n)... implementation as follows:



# Include <iostream> <br/> # include <math. h> <br/> using namespace STD; </P> <p> int get (int n) // returns 1 ~ The number of times that 1 appears in n. The code is concise <br/>{< br/> int lenth = (INT) (log10 (N) + 1, I, j, k = 1, sum = 0; <br/> for (I = 1; I <= lenth; I ++) <br/> {<br/> K * = 10; <br/> sum + = N/K * k/10; <br/> J = (N % K) * 10/K; <br/> If (j> 1) sum + = K/10; <br/> If (j = 1) sum + = (N % K) % (K/10) + 1; <br/>}< br/> return sum; <br/>}</P> <p> int main () <br/> {<br/> int N; <br/> while (CIN> N & N) <br/> cout <get (n) <Endl; <br/>}< br/>



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.