LeetCode -- Count Digit One

Source: Internet
Author: User

LeetCode -- Count Digit One
Description:


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.


This question is purely a regular solution.


For the implementation, see:


// Solution:
// For example '000000 ':
//
// 1-999-> countDigitOne (999)
// 1000-1999-> 1000 of 1 s + countDigitOne (999)
// 2000-2999-> countDigitOne (999)
...
// 7000-7999-> countDigitOne (999)
//
// 8000-8192-> countDigitOne (192)
//
// Count of 1 s: countDigitOne (999) * 8 + 1000 + countDigitOne (192)
//
// Noticed that, if the target is '20160301 ':
//
// Count of 1 s: countDigitOne (999) * 1 + (1192-1000 + 1) + countDigitOne (192)
//
// (1192-1000 + 1) is the 1 s in thousands from 1000 to 1192.


 


Implementation Code:



    public int CountDigitOne(int n) {      if(n <= 0){return 0;}    if(n < 10){return 1;}var result = 0;    var digit = 1;var num = n;    while (num > 0) {          var mod = num % 10;          var sign = mod > 0 ? 1 : 0;          num /= 10;        int a = num * digit;         int b = sign * (mod == 1 ? n % digit + 1: digit);          result += a + b;          digit *= 10;      }      return result;      }


 

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.