MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / getSum

Function getSum

sum_of_two_integers_371/solution.go:4–21  ·  view source on GitHub ↗

Note: study again. Cool problem!

(a int, b int)

Source from the content-addressed store, hash-verified

2
3// Note: study again. Cool problem!
4func getSum(a int, b int) int {
5 for b != 0 {
6 // corresponding bits (1, 1) will need to be set to 0 and carry a 1 over
7 // carry holds the slots where we'll need to carry
8 carry := a & b
9
10 // corresponding bits (1, 0) and (0, 1) will stay set
11 // a no longer has locations of carry bits set via XOR
12 a = a ^ b
13
14 // set b to the result of carrying over each location that we need to carry in
15 // eventually all carries will find a slot in a (may take many carries),
16 // after which b will become 0 and the loop condition will be false.
17 b = carry << 1
18 }
19
20 return a
21}

Callers 1

Test_getSumFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_getSumFunction · 0.68