【力扣】整數的各位積和只差-簡單

超簡單,給Python和C++兩種解法:
1、Python 2、C++
方法:直接遍歷取模

1、C++

class Solution {
public:
    int subtractProductAndSum(int n) {
        int p = 0, t = 1;
        while (n > 0) {
            int digit = n % 10;
            n /= 10;
            p += digit;
            t *= digit;
        }
        return t - p;
    }
};

2、Python

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        add, mul = 0, 1
        while n > 0:
            digit = n % 10
            n //= 10
            add += digit
            mul *= digit
        return mul - add
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章