【LeetCode】兩整數之和
阿新 • • 發佈:2018-12-09
不使用運算子 +
和 -
,計算兩整數 a
、b
之和。
示例 1:
輸入: a = 1, b = 2 輸出: 3
示例 2:
輸入: a = -2, b = 3 輸出: 1
import java.lang.reflect.Array; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int a=sc.nextInt(); int b=sc.nextInt(); System.out.println(Solution.getSum(a,b)); } } class Solution { public static int getSum(int a, int b) { if ((a&b)==0) //沒有進位時 ,返回ab或運算的結果(即a+b) return a|b; return getSum(a^b,(a&b)<<1);//還有進位時 ,a=a^b,b=(a&b)<<1,遞迴運算 } }
思路:兩數相加等價於兩數的二進位制形式不進位和(即異或運算)與進的位(與運算)左移一位再相加(即或運算)。
如:
3+7=10
3=0011
7=0111
3+7=(3^7)+(3&7)<<1即 0011^0111和(0011&0111)<<1相加——> 0100和0110相加
這時候 0100和0110相加還有進位,所以遞迴為:
0100^0110和(0100&0110)<<1相加——>0010和1000相加
這時候0010和1000相加沒有進位了,所以返回的是0010|1000=1010即回到原式3+7的結果等於10。