剑指Offer:整数中 1 出现的次数
题目
分析
就是总结数学规律。
分解让复杂问题变简单。
对于任意给定的 N,分别分析从 1 到 N 在不同位置(个位、十位、百位……) 上累计出现的 1 的个数。 可以发现:
代码
先按上面的想法写了一个智障版本,然后发现根本不需要用到字符串。
智障版本:
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n)
{
if (n == 0) return 0;
int result = 0;
string nstr = to_string(n);
if (nstr[0] == '1') result += (StringToInt(nstr.substr(1)) + 1);
else result += getMulti(nstr.size() - 1);
for (size_t i = 1; i < nstr.size(); ++i) {
int high = StringToInt(nstr.substr(0, i));
int mul = getMulti(nstr.size() - i - 1);
if (nstr[i] == '0')
result += (high * mul);
else if (nstr[i] == '1') {
int low = StringToInt(nstr.substr(i + 1));
result += (high * mul + low + 1);
}
else
result += ((high + 1) * mul);
}
return result;
}
inline int StringToInt(const string& str)
{
return str.empty() ? 0 : stoi(str);
}
inline int getMulti(size_t t)
{
int result = 1;
while (t--) result *= 10;
return result;
}
};
非智障版本
进一步归纳发现高位其实也可以总结到低位里,得到下图。
代码如下:
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n)
{
// 我只是一个可爱的小楼野马,但是 我太难了。其实也可以不用判断 n == 0
if (n == 0) return 0;
int result = 0, mul = 1, low = 0, high = n, d;
while (high > 0) {
d = high % 10;
low = n - high * mul;
high /= 10;
switch(d) {
case 0:
result += high * mul;
break;
case 1:
result += high * mul + low + 1;
break;
default:
result += (high + 1) * mul;
}
mul *= 10;
}
return result;
}
};