[LeetCode] 233. Number of Digit One, leetcode233.number

Source: Internet
Author: User

[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.

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.