Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9bf757e

Browse files
committed
Add C++ solution for leetcode 233.
1 parent 190c699 commit 9bf757e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int countDigitOne(int n) {
9+
if (n == 0) return 0; /* 0 <= n <= 10^9 */
10+
11+
int curDigit;
12+
int count = 0; // 记录1的数量
13+
long highDigt, lastDigit, weigh = 1; // weigh用来记录置1的位置处于个位、十位、百位、千位等...
14+
while (weigh <= n) // weigh每次乘10相对于从低位向高位方向逐位移动,直到超过n时结束循环
15+
{
16+
highDigt = n / (weigh * 10); // 得到某一个位数置1后的商,即当前数之前的部分
17+
lastDigit = n % weigh; // 得到某一位数置1后的余数,即当前数之后的部分
18+
curDigit = (n / weigh) % 10; // 当前置1的位置原来(置1之前)的数
19+
20+
if (curDigit == 0) // 当前位置的数字=0时
21+
count += highDigt * weigh;
22+
if (curDigit == 1) // 当前位置的数字=1时
23+
count += highDigt * weigh + lastDigit + 1;
24+
if (curDigit > 1) // 当前位置的数字>1时
25+
count += (highDigt + 1) * weigh;
26+
27+
weigh *= 10;
28+
}
29+
return count;
30+
}
31+
};
32+
33+
// Test
34+
int main()
35+
{
36+
Solution sol;
37+
int n = 13;
38+
auto res = sol.countDigitOne(n);
39+
cout << res << endl;
40+
41+
return 0;
42+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /