当前位置:网站首页>Sword finger offer 65 Add without adding, subtracting, multiplying, dividing

Sword finger offer 65 Add without adding, subtracting, multiplying, dividing

2022-07-04 22:45:00 LuZhouShiLi

The finger of the sword Offer 65. Do not add, subtract, multiply or divide

subject

  Write a function , Find the sum of two integers , It is required that... Should not be used in the function body “+”、“-”、“*”、“/” Four operation symbols .

Ideas

 Reference resources K God's solution :https://leetcode.cn/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/solution/mian-shi-ti-65-bu-yong-jia-jian-cheng-chu-zuo-ji-7/
  • No carry sum is the same as XOR operation
  • The law of carry and operation is the same ( Need to move one bit left )

Code

class Solution {
    
    public int add(int a, int b) {
    
        while(b != 0)
        {
    
            int c = (a & b) << 1;// c =  carry 
            a ^= b;//  Non carry and   Exclusive or operation 
            b = c;// b =  carry 
        }

        return a;
    }
}
原网站

版权声明
本文为[LuZhouShiLi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042219387801.html