Leetcode 233: Number of Digit One, leetcodedigit

Source: Internet
Author: User

Leetcode 233: Number of Digit One, leetcodedigit
Number of Digit OneTotal Accepted:307Total Submissions:1853

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.

[Idea]

Reference: https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python

Intuitive: each 10 digits, each with 1 bits, every 100 bits, 10 10 digits with 1 bits, every 1000 bits, and 100 bits with 1 bits. create a loop and calculate the total number (one digit, ten digits, and hundreds of digits) of a single bit ).

Example:

Taking the last hundred bits as an example: assume that the last hundred bits is 0, 1, and> = 2:

Case 1: n = 3141092, a = 31410, B = 92. The number of 1 in a hundred bits should be 3141*100 times.

Case 2: n = 3141192, a = 31411, B = 92. The number of 1 in a hundred bits should be 3141*100 + (92 + 1) times.

Case 3: n = 3141592, a = 31415, B = 92. Calculate the number of 1 in a hundred bits (3141 + 1) x 100 times.

The above three cases can be summarized using a formula:

(a + 8) / 10 * m + (a % 10 == 1) * (b + 1);

[CODE]

public class Solution {    public int countDigitOne(int n) {        int ones = 0;        for (long m = 1; m <= n; m *= 10) {            long a = n/m, b = n%m;            ones += (a + 8) / 10 * m;            if(a % 10 == 1) ones += b + 1;        }        return ones;    }}


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.