leetcode371. Sum of Two Integers

    xiaoxiao2023-09-19  3

    //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.

    //solution 1

    int getSum(int a, int b) { if(b) { int c = getSum((a^b), (a&b)<<1); return c; } return a; }

    //solution 2

    int getSum(int a, int b) { int carry; while (b != 0) { carry = (a&b)<<1; a = a^b; b = carry; } return a; }

    // ^表示异或,&是按位与,<<表示左移 //&&和||是逻辑运算符,&和|是位运算符。 //carry控制a和b变化前取值,利用也是类似于递归原理。

    转载请注明原文地址: https://ju.6miu.com/read-1279108.html
    最新回复(0)