Golang concise solution with an explanation


  • 0

    After understanding that a ^ b stands for the sum of each digit (ignoring carry over) and a & b stands for whether carry over occurs on each digit, you will easily see that you need to add carry over (a & b) << 1 repeatedly until no carry over occurred. (Because first carry over may product another carry over, we should do this until no more carry over occurs)

    func getSum(a int, b int) int {
    	sum, co := a^b, a&b
    	for co != 0 {
    		co = co << 1
    		sum, co = sum^co, sum&co
    	}
    	return sum
    }
    
    

Log in to reply
 

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