2544. Alternating Digit Sum

Stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int alternateDigitSum(int n) {
Stack<Integer> stack = new Stack<>();
while (n > 0) {
int num = n % 10;
n /= 10;
stack.push(num);
}

int res = 0;
int sign = 1;
while (!stack.isEmpty()) {
res += sign * stack.pop();
sign *= -1;
}

return res;
}
}

Math

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int alternateDigitSum(int n) {
int res = 0;
int sign = 1;

while (n > 0) {
int num = n % 10;
res += sign * num;
n /= 10;
sign *= -1;
}

return -sign * res;
}
}

References

2544. Alternating Digit Sum