You are given a positive integer n
. Each digit of n
has a sign according to the following rules:
- The most significant digit is assigned a positive sign.
- Each other digit has an opposite sign to its adjacent digits.
Return the sum of all digits with their corresponding sign.
Input: n = 521 Output: 4 Explanation: (+5) + (-2) + (+1) = 4.
Input: n = 111 Output: 1 Explanation: (+1) + (-1) + (+1) = 1.
Input: n = 886996 Output: 0 Explanation: (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
1 <= n <= 109
impl Solution {
pub fn alternate_digit_sum(n: i32) -> i32 {
let mut n = n;
let mut ret = 0;
while n > 0 {
ret = n % 10 - ret;
n /= 10;
}
ret
}
}