GOLANG 0ms with explantation


  • 0
    C

    //we can calculate like adder or summer in digit circut
    // A B C S
    // 0 0 0 0
    // 1 0 0 1
    // 0 1 0 1
    // 1 1 1 0
    //c means carry,we can get c using "&"(and) operator;s means sum,we can get s using "^"(xor)
    //our final result could be calculate by 2*carry+s,and we can use recursion to replace the "+" operator

    package main

    import "fmt"

    func add(a int32, b int32) int32 {
    if a == 0 {
    return b
    }
    if b == 0 {
    return a
    }
    return add(2*(a&b), a^b)
    }

    func main() {
    fmt.Println(add(-20, 3))
    }


Log in to reply
 

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