您的位置:首页 > 其它

[LeetCode] Number of Digit One

2015-07-08 01:50 197 查看
The following idea is taken from a book named 《剑指offer》 published in China.

Suppose
n = 271
, it then breaks
[1, 271]
into
[1, 71]
and
[72, 271]
. For
[72, 271]
, the number of
1
on the hundreds are
10^2 = 100
(note that if the digit on the higest bit is
1
, then the number of
1
's on that bit will be
72
, which is
271 % 100 + 1
). To compute the number of
1
on tens and units, we further break
[72, 271]
into
[72, 171]
and
[172, 271]
. Each interval has
10^1 = 10
1
's on both the tens and units. So the overall number of
1
's on tens and units is
2 * 2 * 10^1 = 40
. Now we are only left with
[1, 71]
, which can be solved recursively. The
int n
is transformed into a
string num
to facilitate some operations.

The code is as follows.

class Solution {
public:
int countDigitOne(int n) {
if (n <= 0) return 0;
string num = to_string(n);
return countOne(num);
}
private:
int countOne(string num) {
if (num.empty()) return 0;
int first = num[0] - '0';
if (num.length() == 1) {
if (first) return 1;
return 0;
}
int highestBit;
if (first > 1) highestBit = powerTen(num.length() - 1);
else if (first == 1) highestBit = stoi(num.substr(1)) + 1;
int otherBits = first * (num.length() - 1) * powerTen(num.length() - 2);
int recurCount = countOne(num.substr(1));
return highestBit + otherBits + recurCount;
}
int powerTen(int exp) {
int p = 1;
for (int i = 0; i < exp; i++)
p *= 10;
return p;
}
};


This link has a brilliant 4-line solution! The code is rewritten as follows.

class Solution {
public:
int countDigitOne(int n) {
int counts = 0;
for (int m = 1000000000; m; m /= 10)
counts += (n / m + 8) / 10 * m + (n / m % 10 == 1) * (n % m + 1);
return counts;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: