[Leetcode] [JavaScript] Number of Digit One

Source: Internet
Author: User
Tags pow

Number of Digit One

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.

Maths problem, it's really embarrassing for me to be a math clumsy.

Recursive division, take 8192 to raise chestnuts:

Split the 8192 into:

1-999, recursion (999)

1000-1999-1000 1 + recursion (999)

2001-2999, recursion (999)

.

.

8000-8192, recursion (192)

Total is: recursive (999) *8 + 1000 + recursive (192)

Notice that if it's 1192,

Total: Recursive (999) * + (1000-192 + 1) + recursive (192)

(1000-192 + 1) is 1 of the thousands on the 1000-1192.

1 /**2 * @param {number} n3 * @return {number}4  */5 varCountdigitone =function(n) {6     if(n <= 0){7         return0;8}Else if(N < 10){9         return1;Ten     } One     varLen =n.tostring (). length; A     varBase = Math.pow (Ten, len-1); -     varAnswer = parseint (N/base); -     varremainder = n%Base; the     varOneinbase = 0; -     if(Answer = = 1){ -Oneinbase = n-base + 1; -}Else{ +Oneinbase =Base; -     } +     returnCountdigitone (base-1) * answer + oneinbase +countdigitone (remainder); A};

Then less open a few variables, forced to write code on one line, in the actual project do not do so oh, after a period of time you can not understand.

1 /**2 * @param {number} n3 * @return {number}4  */5 varCountdigitone =function(n) {6     if(n <= 0)return0;7     if(N < 10)return1;8     varBase = Math.pow (Ten, N.tostring (). length-1);9     varAnswer = parseint (N/base);Ten     returnCountdigitone (base-1) * answer + (answer = = = 1?) (N-base + 1): Base) + countdigitone (n%base); One};

[Leetcode] [JavaScript] 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.