算法Week02.03 - LeetCode 371. Sum of Two Integers
来源:互联网 发布:知乎怎么修改关注话题 编辑:程序博客网 时间:2024/06/05 19:21
题目大意
实现两个整数的加法操作,但不准使用 +
或 -
操作。
解题思路
乍一看觉得有些不知所措…
不过转念一想,啊哈,数电学的逻辑操作终于用得上场了…\笑cry。数电全加器的加法是逐位的,在程序语言里我们不方便做到,不过可以采用如下操作:
- A xor B = C
- A & B = Carry
- if Carry != 0 then A <- C, B <- (Carry << 1) jump to 1
else stop
注意将进位赋值给B时要左移一位。
完整代码
class Solution {public: int getSum(int a, int b) { int sum = a ^ b; int carry = (a & b) << 1; while (carry) { a = sum; sum = a ^ carry; carry = (a & carry) << 1; } return sum; }};
0 0
- 算法Week02.03 - LeetCode 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers LeetCode OJ
- [Leetcode]371. Sum of Two Integers
- LeetCode - 371. Sum of Two Integers
- <LeetCode OJ> 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- leetcode 371. Sum of Two Integers
- leetcode 371.Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers(Leetcode)
- leetcode 371. Sum of Two Integers
- 【leetcode】371. Sum of Two Integers【E】
- [leetcode] 371. Sum of Two Integers
- leetcode.371. Sum of Two Integers
- 371. Sum of Two Integers--LeetCode Record
- LeetCode—371. Sum of Two Integers
- Leetcode 371. Sum of Two Integers
- jdbc 操作数据库,数据库连接池
- Codeforces #370 (Div.2) B. Memory and Trident【思维】
- python代码规范
- 基于数据驱动的接口自动化测试解决方案
- 多线程模拟实现生产者/消费者模型
- 算法Week02.03 - LeetCode 371. Sum of Two Integers
- Quartz.NET教程_Lesson 1: Using Quartz
- java 常见面试题及答案
- leetcode之258. Add Digits(C++解法)
- SLAM代码(光流法)
- leetcode之242. Valid Anagram(C++解法)
- 关于android 联系人,短信,电话记录,需要的uri,数据库中获取的小结,请看注释
- js学习笔记:语句和函数
- 带你解析Dagger2