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