Skip to content

Commit 00f4cb5

Browse files
authored
Create alternating-digit-sum.cpp
1 parent d08966f commit 00f4cb5

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

C++/alternating-digit-sum.cpp

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Time: O(logn)
2+
// Space: O(1)
3+
4+
// math
5+
class Solution {
6+
public:
7+
int alternateDigitSum(int n) {
8+
int result = 0, sign = 1;
9+
for (; n; n /= 10) {
10+
sign *= -1;
11+
result += sign * (n % 10);
12+
}
13+
return sign * result;
14+
}
15+
};

0 commit comments

Comments
 (0)