LeetCode——two sum of integer
来源:互联网 发布:伪随机算法 编辑:程序博客网 时间:2024/04/29 23:03
- 题目描述:对两个整数求和,不能直接用“+”和“-”
- 题目分析:当我看到这个题目表示一脸懵逼,第一次在LeetCode上刷题,之前是看都没看到过,根本不知道别人说LeetCode上的题目是个什么鬼,今天有时间了看了一下,看到求和,按照我之前的想法,肯定是用+和-来的容易些,但是题目不让用,就表示不知从何下手,我试了下用for循环,让一个整数自加另一个整数次,其实这样做和用+的本质一样,都是会出现超过整型的表示范围的时候就不能用了,因为第一次,思路也不开阔,所以就在网上搜了答案,采用别人提供的两种方法来做
- 做法一:采用位运算(异或+移位)
public class Solution { public int getSum(int a, int b) { while (b != 0) { int c = a ^ b; b = (a & b) << 1; a = c; } return a; }}
做法二:位运算:(模拟加法)
public class Solution { public int getSum(int a, int b) { int r = 0, c = 0, p = 1; while ((a | b | c) != 0) { if (((a ^ b ^ c) & 1) != 0) r |= p; p <<= 1; c = (a & b | b & c | a & c) & 1; a >>>= 1; b >>>= 1; } return r; }}
这里采用 的方法是加法的最本质的运算,用二进制位的移位运算来做!我的印象还是计算机组成原理里学过,需要回顾学习!
0 0
- LeetCode——two sum of integer
- LeetCode—371. Sum of Two Integers
- Sum—LeetCode-371 Sum of Two Integers
- Sum of two integer number
- LeetCode — Two Sum
- LeetCode—Two Sum
- LeetCode—Two Sum
- leetcode—Two Sum
- LeetCode —-Two Sum
- 【Leetcode】Sum of Two Integers
- leetcode Sum of Two Integers
- LeetCode---Sum of Two Integers
- LeetCode:Sum of Two Integers
- 371.[LeetCode]Sum of Two
- LeetCode:Sum of Two Integers
- LeetCode Sum of Two Integers
- Leetcode Sum of Two Integers
- Leetcode Sum of Two Intergers
- Class文件的加载过程
- java编程习惯
- (有参考基因组)植物转录组分析之一数据处理
- 【leetcode】15. 3Sum
- genymotion unable to start the device的解决方案
- LeetCode——two sum of integer
- 【C#】Excel导出合并行和列并动态加载行与列
- 安卓中的自定义ListView学习总结
- 计算机原理(四)
- Led驱动程序及应用程序编写
- Matlab的函数调用和参数传递
- jQuery ajax教程
- 链表和顺序表的一些区别
- Android中的Application