Leetcode之路 371. Sum of Two Integers
来源:互联网 发布:酷炫爆炸js网站效果 编辑:程序博客网 时间:2024/06/02 06:09
1、题目描述
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.
Tags:
Bit_Manipulation
2、Java代码实现
public class Solution { public int getSum(int a, int b) { if(a==0) return b; if(b==0) return a; while(b!=0){ int carry=a&b; a=a^b; b=carry<<1; } return a; }}
3、经验教训
- 后悔当初没好好学数字逻辑和组成原理,对Bit的操作都不熟练……
- Leetcode中一个比较好的discuss: Java simple easy understand solution with explanation,以下是其中代码:
// Iterativepublic int getSum(int a, int b) { if (a == 0) return b; if (b == 0) return a; while (b != 0) { int carry = a & b; a = a ^ b; b = carry << 1; } return a;}// Iterativepublic int getSubtract(int a, int b) { while (b != 0) { int borrow = (~a) & b; a = a ^ b; b = borrow << 1; } return a;}// Recursivepublic int getSum(int a, int b) { return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);}// Recursivepublic int getSubtract(int a, int b) { return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1);}// Get negative numberpublic int negate(int x) { return ~x + 1;}
0 0
- Leetcode之路 371. Sum of Two Integers
- LeetCode之路:371. Sum of Two Integers
- LeetCode之Sum of Two Integers
- leetcode之371. Sum of Two Integers(C++解法)
- 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
- webView 在解析html中自动调整大小
- LeetCode 110. Balanced Binary Tree
- hdu 1547 Bubble Shooter(DFS)
- 前后端分离,实现post请求
- UITabBarController的 tabBar 高度动态调节
- Leetcode之路 371. Sum of Two Integers
- jira中issue状态的改变触发Jenkins构建
- 运维日记009 - 认识Linux上的桑巴舞——Samba
- LeetCode 33 Search in Rotated Sorted Array
- 进程间通信(IPC)以及同步
- HDU 3537 Daizhenyang's Coin
- Android Frequently Asked Questions for Open Source
- 使用secureCRT连接服务器,防超时断开
- iOS 本地化入门教程