2544.交替数字和
链接:2544.交替数字和
难度:Easy
标签:数学
简介:返回所有数字及其对应符号的和。
题解 1 - rust
- 编辑时间:2023-01-22
- 内存消耗:2MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn alternate_digit_sum(n: i32) -> i32 {
        let mut n = n;
        let mut ans = 0;
        let mut f = if n.to_string().len() % 2 == 0 { -1 } else { 1 };
        while n > 0 {
            ans += f * (n % 10);
            f *= -1;
            n /= 10;
        }
        return ans;
    }
}
题解 2 - cpp
- 编辑时间:2023-07-12
- 执行用时:4ms
- 内存消耗:5.7MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    int alternateDigitSum(int n) {
        int len = to_string(n).size(), res = 0, cur = 1;
        if (len % 2 == 0) cur *= -1; 
        while (n) {
            res += (n % 10) * cur;
            cur *= -1;
            n /= 10;
        }
        return res;
    }
};
题解 3 - python
- 编辑时间:2023-01-22
- 执行用时:32ms
- 内存消耗:15MB
- 编程语言:python
- 解法介绍:遍历。
class Solution:
def alternateDigitSum(self, n: int) -> int:
    ans = 0
    f = 1
    if len(str(n)) % 2 == 0:
        f = -1
    while n:
        ans += f * (n % 10)
        f *= -1
        n //= 10
    return ans