一切源于leetcode 258---Add Digits这道题,https://leetcode.com/problems/add-digits/
题目的解法很简单,有两种公式,一种是我这种笨笨的人写的:
class Solution {
public:
int addDigits(int num) {
if(num==0)
return 0;
if(num%9!=0)
return num%9;
return 9;
}
};
一种是天才们想出来的解法:
class Solution {
public:
int addDigits(int num) {
return 1+((num-1)%9);
}
};
我很疑惑当0的时候,(-1)%9=-1???
于是查了查:《关键是这句话:By implication, if m%n is nonzero, it has the same sign as m. 》同时Java和C++用的一样的计算方法。
C++ Primer 5th:
The % operator, known as the “remainder” or the “modulus” operator, computes the remainder that results from dividing the left-hand operand by the right-hand operand. The operands to % must have integral type.
In a division, a nonzero quotient is positive if the operands have the same sign and negative otherwise. Earlier versions of the language permitted a negative quotient to be rounded up or down; the new standard requires the quotient to be rounded toward zero (i.e., truncated).
The modulus operator is defined so that if m and n are integers and n is nonzero, then (m/n)*n + m%n is equal to m. By implication, if m%n is nonzero, it has the same sign as m. Earlier versions of the language permitted m%n to have the same sign as n on implementations in which negative m/n was rounded away from zero, but such implementations are now prohibited. Moreover, except for the obscure case where -m overflows, (-m)/n and m/(-n) are always equal to -(m/n), m%(-n) is equal to m%n,
and (-m)%n is equal to -(m%n). More concretely:
Code:
21 % 6; /* result is 3 */
21 % 7; /* result is 0 */
-21 % -8; /* result is -5 */
21 % -5; /* result is 1 */
21 / 6; /* result is 3 */
21 / 7; /* result is 3 */
-21 / -8; /* result is 2 */
21 / -5; /* result is -4 */