?371. Sum of Two Integers(C++)

来源:互联网 发布:手机淘宝老版本官方 编辑:程序博客网 时间:2024/06/06 15:53

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.

class Solution {public:    int getSum(int a, int b) {        return b == 0 ? a : getSum(a ^ b, (a & b) << 1);    }};

https://discuss.leetcode.com/topic/50315/a-summary-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently
补充位运算符相关知识:
Set negation ALL_BITS ^ A or ~A
Set bit A |= 1 << bit
Clear bit A &= ~(1 << bit)
Test bit (A & 1 << bit) != 0
Extract last bit A&-A or A&~(A-1) or x^(x&(x-1))
Remove last bit A&(A-1)
Get all 1-bits ~0
Examples

//Count the number of ones in the binary representation of the given numberint count_one(int n) {    while(n) {        n = n&(n-1);        count++;    }    return count;}
//Is power of four (actually map-checking, iterative and recursive methods can do the same)bool isPowerOfFour(int n) {    return !(n&(n-1)) && (n&0x55555555);    //check the 1-bit location;}
原创粉丝点击