leetcode 258. Add Digits /371. Sum of Two Integers

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

class Solution {
public:
    int addDigits(int num) 
    {
          return (num-1)%9 +1;
    }
};
  1. Sum of Two Integers
    Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
    Example:
    Given a = 1 and b = 2, return 3.

解题思路
“&” AND operation, for example, 2 (0010) & 7 (0111) => 2 (0010)
“^” XOR operation, for example, 2 (0010) ^ 7 (0111) => 5 (0101)
“~” NOT operation, for example, ~2(0010) => -3 (1101) what??? Don’t get frustrated here. It’s called two’s complement.
1111 is -1, in two’s complement
1110 is -2, which is ~2 + 1, ~0010 => 1101, 1101 + 1 = 1110 => 2
1101 is -3, which is ~3 + 1
so if you want to get a negative number, you can simply do ~x + 1
Reference:
https://en.wikipedia.org/wiki/Two%27s_complement
https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html
For this, problem, for example, we have a = 1, b = 3,
In bit representation, a = 0001, b = 0011,
First, we can use “and”(“&”) operation between a and b to find a carry.
carry = a & b, then carry = 0001
Second, we can use “xor” (“^”) operation between a and b to find the different bit, and assign it to a,
Then, we shift carry one position left and assign it to b, b = 0010.
Iterate until there is no carry (or b == 0)

class Solution {
public:
    int getSum(int a, int b) 
    {
       while(b!=0)
       {
           int carry = a&b;
           //int carry = (~a) &b
            a = a^b;
           b = carry << 1;
       }
        return a;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值