2544. Alternating Digit Sum ¶ Time: $O(\log n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class Solution { public: int alternateDigitSum(int n) { int ans = 0; int sign = 1; for (; n > 0; n /= 10) { sign *= -1; ans += sign * n % 10; } return sign * ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13class Solution { public int alternateDigitSum(int n) { int ans = 0; int sign = 1; for (; n > 0; n /= 10) { sign *= -1; ans += sign * n % 10; } return sign * ans; } } 1 2 3 4 5 6 7 8 9 10 11class Solution: def alternateDigitSum(self, n: int) -> int: ans = 0 sign = 1 while n > 0: sign *= -1 ans += n % 10 * sign n //= 10 return sign * ans