Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
若 a ≡ b (mod m),x ≡ y (mod m),则 a + x ≡ b + y (mod m)
显然对任意自然数 n,a ≡ a * 10 ^ n (mod 9)
因此对 A = a[0] + a[1] * 10 + a[2] * 100 + ... + a[n] * 10 ^ n
其各数位上数字和 B = a[0] + a[1] + a[2] + ... + a[n]
有 A ≡ B (mod 9),即 (A - B) % 9 == 0
(A - B) % 9 == 0
若 B < 9,则 B = A % 9
若 B == 9,则 A % 9 == 0
class Solution {
public:
int addDigits(int num) {
if (!num) {
return 0;
}
int res = num % 9;
if (!res) {
return 9;
}
return res;
}
};