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>Given a = 1 and b = 2, return 3.
這題難在不能使用 + 和 -,所以剩下的選擇是使用 bit operation
這裡有一篇統整,非常實用
想法如下
- 用 a ^ b 找到 0 + 0 或 0 + 1 的位置
- 用 a & b 找到 1 + 1 的位置,並往左進一位
Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int getSum(int a, int b) { | |
return b == 0 ? a : getSum(a^b, (a&b) << 1); | |
} | |
} |
kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
沒有留言:
張貼留言