LeetCode 371(Sum of Two Integers)
来源:互联网 发布:淘宝真实姓名怎么改 编辑:程序博客网 时间:2024/06/06 01:07
371. Sum of Two Integers
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.
首先水一波,自己写的牛头不对马嘴,丝毫不体现编程的代码。竟然也能通过.....
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
c=[]
c.append(a)
c.append(b)
return sum(c)
这个应该是sum内部的程序是用逻辑做出来的吧。
下面说一下正确的关于重要知识的代码吧。这里参考http://blog.csdn.net/liyuanbhu/article/details/51803974这个博客专家写的,加入了自己的理解。
不用加减法计算两个整数的和。这道题其实是考察一些基本的布尔代数知识。我们知道,二进制表示时:
0 + 0 = 00
1 + 0 = 01
0 + 1 = 01
1 + 1 = 10
所以,两个二进制整数
所以有如下关系:
如果
设
那么有 ,这时,将a+b转换为x0+c0,但是我们仍然不能用+号啊,所以继续做变换,直到c0为为0时,此时表示没有进位了,只剩下某个Xn,这时结果
只是Xn,不用加上Cn了,就不需要为+号而烦恼了。
那么有:
并且
那么,只要
下面说一下正确的关于重要知识的代码吧。这里参考http://blog.csdn.net/liyuanbhu/article/details/51803974这个博客专家写的,加入了自己的理解。
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
if a==0:return b
else:
x=a^b
c=(a&b)<<1
return self.getSum(c,x) #这里注意词c,x与a,b要对应,a==0对应c==0
s=Solution()
print s.getSum(2,3)
0 0
- LeetCode(371) Sum of Two Integers
- LeetCode 371(Sum of Two Integers)
- LeetCode 371 Sum of Two Integers
- [leetcode-371]Sum of Two Integers(java)
- LeetCode[371] Sum of Two Integers
- LeetCode 371 : Sum of Two Integers(Java)
- leetcode NO.371 sum of two integers
- LeetCode#371 Sum of Two Integers
- leetcode 371 Sum of Two Integers C++
- LeetCode 371: Sum of Two Integers 题解
- leetcode:bits:Sum of Two Integers(371)
- [LeetCode-371]Sum of Two Integers(C)
- LeetCode 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
- [Leetcode] #371 Sum of Two Integers
- c++笔记(tips)(1)
- 带分数(排列组合)
- struts2.5框架使用通配符指定方法(常见错误)
- 定义的数组过大,程序运行结果为空?
- 复杂指针解析
- LeetCode 371(Sum of Two Integers)
- 求一个3*3矩阵对角线元素之和
- 强制类型转换
- 深度学习 知识汇总
- HEVC YUV数据的获取
- 看程序员女盆友怎样吐槽男票的!
- CC算法设计(1)
- 使用FileReader与FileWriter读写数据
- 用Navicat for Mysql导入.sql文件