leetcode 258---Add Digits, 关于C++中负数取余

一切源于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 */


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值