"Leetcode" 233. Number of Digit One

Source: Internet
Author: User

Title:

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.

Code:
Class Solution {public:    int countdigitone (int n) {        int ones = 0;        For (long long m = 1; M <= n; m *=) {            ones + = (n/m + 8)/ten * m + (n/m% = = 1) * (n% m + 1);        }        return ones;}    ;
Tips:

We give the code first, and we analyze it. The body logic of the code is parsed from the lowest bit to the left.

Because for each person, there are several situations that need to be discussed separately, namely:

    • The bit is greater than 1: if it is greater than 1, then the number of times that the bit appears 1 is (n/m + 8)/ten * M
    • The bit is 0: if the bit is 0, then in the above equation (n/m + 8)/ten * M , +8 does not produce a carry, so the correct answer can still be obtained
    • This bit is 1: If the bit is 1, then although the above formula will still not carry, but we also need to add the number of lower part, so there will be:(n/m% = = 1) * (n% m + 1)

"Leetcode" 233. 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.