Leetcode 503,Add two numbers without using arithmetic operators
2016-11-12 10:26
429 查看
int add(int x, int y) {
// Iterate till there is no carry
while (y != 0) {
// carry now contains common set bits of x and y
int carry = x & y;
// Sum of bits of x and y where at least one of the bits is not set
x = x ^ y;
// Carry is shifted by one so that adding it to x gives the required sum
y = carry << 1;
}
return x;
}
//Following is recursive implementation for the same approach
int add2(int x, int y) {
if (y == 0){
return x;
}else {
return add2( x ^ y, (x & y) << 1);
}
}
refer: http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/
// Iterate till there is no carry
while (y != 0) {
// carry now contains common set bits of x and y
int carry = x & y;
// Sum of bits of x and y where at least one of the bits is not set
x = x ^ y;
// Carry is shifted by one so that adding it to x gives the required sum
y = carry << 1;
}
return x;
}
//Following is recursive implementation for the same approach
int add2(int x, int y) {
if (y == 0){
return x;
}else {
return add2( x ^ y, (x & y) << 1);
}
}
refer: http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/
相关文章推荐
- Add two numbers without using arithmetic operators
- add two numbers without using +
- LeetCode 2.Add Two Numbers 3.Longest Substring Without Repeating Characters 解析
- LeetCode 2.Add Two Numbers & 3.Longest Substring Without Repeating Characters
- 52. 不用+、-、×、÷做加法[add two numbers without arithmetic]
- LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters
- LeetCode : Add Two Numbers [java]
- LeetCode 2 Add Two Numbers
- 【LeetCode】Add Two Numbers
- Leetcode – Add Two Numbers (Java)
- LeetCode java实现Add Two Numbers
- 【leetcode】Add Two Numbers
- Leetcode[2] Add Two Numbers
- LeetCode 2 Add Two Numbers 模拟,读题 难度:0
- 2015-05-23 LeetCode 2: Add Two Numbers 个人总结
- LeetCode:Add Two Numbers
- leetcode 2. Add Two Numbers
- leetcode 2. Add Two Numbers
- Leetcode_002_Add_Two_Numbers
- leetcode题解-2. Add Two Numbers