[Leetcode]233.number of Digit One

Source: Internet
Author: User

Topic

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.

Ideas

[Number of 32]1 of the algorithm series

Code

/ *---------------------------------------* Date: 2015-07-19* sjf0115* title: 233.Number of Digit one* website: Https://lee tcode.com/problems/number-of-digit-one/* Result: ac* Source: leetcode* Blog:-----------------------------------------*/#include <iostream>#include <vector>usingNamespace Std;class Solution { Public:int Countdigitone(intN) {if(n = =0){return 0; }//if        intresult =0;intLowernum =0, Curnum =0, Highnum =0;int Base=1;intnum = n; while(num) {//Low partLowernum = N-num *Base;//Current SectionCurnum = num%Ten;//High partHighnum = num/Ten;//If 0 then the number of occurrences of this bit 1 is determined by a higher (higher number * current digit)            if(Curnum = =0) {result + = Highnum *Base; }//if            //If 1 the number of occurrences of this bit 1 is not only affected by higher levels but also by low (higher digits * current digits + low number + 1)            Else if(Curnum = =1) {result + = Highnum *Base+ (Lowernum +1); }//else            //greater than 1 is only affected by higher ((higher number + 1) * Current digits)            Else{result + = (Highnum +1) *Base; }//elseNum/=Ten;Base*=Ten; }//while        returnResult }};intMain () {solution S;intN while(cin>>n)    {cout<<s.countdigitone (n) <<endl; }//while    return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Leetcode]233.number of Digit One

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: info-contact@alibabacloud.com 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.