Skip to content

Commit

Permalink
Create alternating-digit-sum.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Jan 24, 2023
1 parent d08966f commit 00f4cb5
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions C++/alternating-digit-sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Time: O(logn)
// Space: O(1)

// math
class Solution {
public:
int alternateDigitSum(int n) {
int result = 0, sign = 1;
for (; n; n /= 10) {
sign *= -1;
result += sign * (n % 10);
}
return sign * result;
}
};

0 comments on commit 00f4cb5

Please sign in to comment.