[LeetCode] 233. Number of Digit One, leetcode233.number
Question
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
[Of algorithm series] Number of 1
Code
/* ------------------------------------- * Date: 2015-07-19 * Author: SJF0115 * Subject: 233. number of Digit One * URL: Warning result: AC * Source: LeetCode * blog: ------------------------------------------- */# include <iostream> # include <vector> using namespace std; class Solution {public: int countDigitOne (int n) {if (n = 0) {return 0 ;}// if int result = 0; int lowerNum = 0, curNum = 0, highNum = 0; int base = 1; int num = n; while (num) {// low part lowerNum = n-num * base; // current part curNum = num % 10; // high part highNum = num/10; // if the value is 0, the number of occurrences of this 1 digit is determined by a higher value (a higher digit * The current digit) if (curNum = 0) {result + = highNum * base ;} // if the value is 1, the number of occurrences of this digit 1 is not only affected by the higher position, but also by the lower position (higher digit * Current digit + lower digit + 1) else if (curNum = 1) {result + = highNum * base + (lowerNum + 1 );} // else // if the value is greater than 1, The else is only affected by the higher level (higher level Number + 1) * Current digit) else {result + = (highNum + 1) * base ;} // else num/= 10; base * = 10;} // while return result ;}}; int main () {Solution s; int n; while (cin> n) {cout <s. countDigitOne (n) <endl;} // while return 0 ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.