《Cracking the Coding Interview》——第18章:难题——题目1
2014-04-29 00:59
411 查看
2014-04-29 00:56
题目:不用算数运算,完成加法。
解法:那就位运算吧,用加法器的做法就可以了。
代码:
题目:不用算数运算,完成加法。
解法:那就位运算吧,用加法器的做法就可以了。
代码:
// 18.1 add two numbers wihout using arithmetic operator. #include <iostream> using namespace std; int add(int x, int y) { int sum; int carry; int bx, by; int base; base = 1; carry = 0; sum = 0; while (base != 0) { bx = x & base; by = y & base; base <<= 1; sum |= ((bx) ^ (by) ^ carry); carry = ((bx & by) || (bx & carry) || (by & carry)) ? base : 0; } return sum; } int main() { int x, y; while (cin >> x >> y) { cout << add(x, y) << endl; } return 0; }
相关文章推荐
- 《Cracking the Coding Interview》——第18章:难题——题目13
- 《Cracking the Coding Interview》——第18章:难题——题目2
- 《Cracking the Coding Interview》——第18章:难题——题目3
- 《Cracking the Coding Interview》——第18章:难题——题目4
- 《Cracking the Coding Interview》——第18章:难题——题目5
- 《Cracking the Coding Interview》——第18章:难题——题目6
- 《Cracking the Coding Interview》——第18章:难题——题目7
- 《Cracking the Coding Interview》——第18章:难题——题目8
- 《Cracking the Coding Interview》——第18章:难题——题目9
- 《Cracking the Coding Interview》——第18章:难题——题目10
- 《Cracking the Coding Interview》——第18章:难题——题目11
- 《Cracking the Coding Interview》——第18章:难题——题目12
- 《Cracking the Coding Interview》题目汇总
- 《Cracking the Coding Interview》——第2章:链表——题目7
- 《Cracking the Coding Interview》——第4章:树和图——题目9
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目7
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目8
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目3
- 《Cracking the Coding Interview》——第12章:测试——题目3
- 《Cracking the Coding Interview》——第17章:普通题——题目11