Why this code not work correctly?


  • 0
    H

    Please give me some advice,thanks!
    """
    class Solution{
    public:
    int getSum(int a, int b){
    int s, c;
    s = a ^ b;
    c = a & b;
    while(c != 0){
    c = c << 1;
    s = s ^ c;
    c = s & c;
    }
    return s;
    }
    };
    """


  • 0
    S

    @huanghao_bupt I did quite the same things as u. The first problem is about u need to create a variable to temporarily save the value of s before running c = s & c , for example, temp_s = s ^ c, But the further problem is this solution can only sum up two positive numbers. When a negative appears, the error just comes with it.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.