Skip to main content
Back to problems
#2544
Easy Algorithms

Alternating digit sum

Math
69.0% acceptance
Feb 25, 2026
478
23
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn alternate_digit_sum(n: i32) -> i32 {
    let digits: Vec<i32> = {
      let mut v = Vec::new();
      let mut m = n;
      while m > 0 {
        v.push(m % 10);
        m /= 10;
      }
      v.reverse();
      v
    };
    digits
      .iter()
      .enumerate()
      .map(|(i, &d)| if i % 2 == 0 { d } else { -d })
      .sum()
  }
}