2017年12月15日 星期五

[LeetCode] 371. Sum of Two Integers

轉自LeetCode

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>

這題難在不能使用 +  和 -,所以剩下的選擇是使用 bit operation

這裡有一篇統整,非常實用

想法如下
  • 用 a ^ b 找到 0 + 0 或 0 + 1 的位置
  • 用 a & b 找到 1 + 1 的位置,並往左進一位
code 如下

Java
class Solution {
public int getSum(int a, int b) {
return b == 0 ? a : getSum(a^b, (a&b) << 1);
}
}

kotlin
class Solution {
fun getSum(a: Int, b: Int): Int {
var num1 = a
var num2 = b
var tmpNum1 = 0
while(num2 != 0) {
tmpNum1 = num1 xor num2 // sum
num2 = (num1 and num2) shl 1 // carry
num1 = tmpNum1
}
return num1
}
}

沒有留言:

張貼留言