LeetCode 题解(148): Number of Digit One

来源:互联网 发布:网络存储器怎么用 编辑:程序博客网 时间:2024/05/18 13:23

题目:

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.

Hint:

  1. Beware of overflow.
题解:

参见 Google经典面试题:求从1到n的n个整数中,字符“1”出现的个数

C++版:

class Solution {public:    int countDigitOne(int n) {        int num = 0, prefix = 0, suffix = 0;        int temp = n, mask = 1;        while(temp > 0) {            int lastDigit = temp % 10;            prefix = temp / 10;            suffix = n % (temp * mask);            num += prefix * mask;            if(lastDigit > 1)                num += mask;            else if(lastDigit == 1)                num += suffix + 1;            temp /= 10;            mask *= 10;        }        return num;    }};

Java版:

public class Solution {    public int countDigitOne(int n) {        int temp = n, mask = 1;        int prefix = 0, suffix = 0, currentDigit = 0, result = 0;        while(temp > 0) {            currentDigit = temp % 10;            prefix = temp / 10;            suffix = n % (temp * mask);            result += prefix * mask;            if(currentDigit == 1)                result += (suffix + 1);            else if(currentDigit > 1)                result += mask;            temp /= 10;            mask *= 10;        }        return result;    }}

Python版:

class Solution:    # @param {integer} n    # @return {integer}    def countDigitOne(self, n):        result, temp, mask, prefix, suffix, current = 0, n, 1, 0, 0, 0        while temp > 0:            prefix = temp / 10            current = temp % 10            suffix = n % (temp * mask)            result += prefix * mask            if current == 1:                result += (suffix + 1)            elif current > 1:                result += mask            mask *= 10            temp /= 10        return result


0 0