LintCode A + B Problem
原题链接在这里:http://www.lintcode.com/en/problem/a-b-problem/
不让用 数学运算符,就用位运算符。
a的对应位 ^ b的对应位 ^ carry 就是res中的对应位。
carry 更新为0还是1要分别讨论。
Time Complexity: O(1), 一共32位. Space: O(1).
AC Java:
1 class Solution { 2 /* 3 * param a: The first integer 4 * param b: The second integer 5 * return: The sum of a and b 6 */ 7 public int aplusb(int a, int b) { 8 // write your code here, try to do it without arithmetic operators. 9 int res = 0; 10 int carry = 0; 11 for(int i = 0; i<32; i++){ 12 int aCur = (a>>i) & 1; 13 int bCur = (b>>i) & 1; 14 res |= (aCur ^ bCur ^ carry) << i; 15 if((aCur == 1 && bCur == 1) || ((aCur == 1 || bCur == 1) && carry == 1)){ 16 carry = 1; 17 }else{ 18 carry = 0; 19 } 20 } 21 return res; 22 } 23 };