# leetcode 日经贴，Cpp code -Number of Digit One

Number of Digit One

class Solution {
public:
int countDigitOne(int n) {
if (n <= 0) return 0;
vector<int> vi;
while (n) {
vi.push_back(n % 10);
n /= 10;
}
reverse(vi.begin(), vi.end());
int a = 0, b = 0, lenvi = vi.size();
int ret = 0;
for (int i = 0; i < lenvi; ++i) {
int powerb = 1;
b = 0;
for (int j = i + 1; j < lenvi; ++j) {
powerb *= 10;
b = b * 10 + vi[j];
}
if (vi[i] > 1) {
ret += (a + 1) * powerb;
} else if (vi[i] == 1) {
ret += a * powerb + b + 1;
} else {
ret += a * powerb;
}
a = a * 10 + vi[i];
}
return ret;
}
};
class Solution {
public:
int countDigitOne(int n) {
if (n <= 0) {
return 0;
}
int count1s = 0;
vector<int> digits;
while (n) {
digits.push_back(n % 10);
n /= 10;
}
int sz = digits.size();
vector<int> pow10(sz), lowval(sz);
pow10[0] = 1;
lowval[0] = 0;
for (int i = 1; i < digits.size(); ++i) {
pow10[i] = pow10[i - 1] * 10;
lowval[i] = lowval[i - 1] + digits[i - 1] * pow10[i - 1];
}
int highval = 0;
for (int i = sz - 1; i >= 0; --i) {
if (digits[i] > 1) {
count1s += (highval + 1) * pow10[i];
} else if (digits[i] == 1) {
count1s += highval * pow10[i] + lowval[i] + 1;
} else {
count1s += highval * pow10[i];
}
highval = highval * 10 + digits[i];
}
return count1s;
}
};

07-08 1.5万

08-24 946

05-06 14

03-28 1.6万

08-07 1779

05-06 204

08-29 1341

04-20 194

04-14 178

04-22 186