Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf47cbc0

Browse files
authored
Merge pull requestJack-Lee-Hiter#1 from Sen1992/Sen1992-patch-1
Update 不用加减乘除做加法.py
2 parentsf1b9f60 +ae60086 commitf47cbc0

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

‎Target Offer/不用加减乘除做加法.py

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,24 @@
66
# 可能是python的的整型可以无限大的原因, 导致正数和负数的异或操作不断变成更小的负数而不会溢出
77
# 使用Swift尝试了一下, 还是可以求得正数和负数的位操作相加运算的
88
# -*- coding:utf-8 -*-
9+
# class Solution:
10+
# def Add(self, num1, num2):
11+
# while num2:
12+
# sum = num1 ^ num2
13+
# carry = (num1 & num2) << 1
14+
# num1 = sum
15+
# num2 = carry
16+
# return num1
17+
# s = Solution()
18+
# print(s.Add(4, 2))
19+
# -*- coding:utf-8 -*-
20+
# 通过每次对num1进行与操作保证是一个32位的整形
21+
# 因此最后我们可以判断符号位是否为1做处理
922
classSolution:
1023
defAdd(self,num1,num2):
11-
whilenum2:
12-
sum=num1^num2
13-
carry= (num1&num2)<<1
14-
num1=sum
15-
num2=carry
16-
returnnum1
17-
s=Solution()
18-
print(s.Add(4,2))
24+
# write code here
25+
whilenum2!=0:
26+
temp=num1^num2
27+
num2= (num1&num2)<<1
28+
num1=temp&0xFFFFFFFF
29+
returnnum1ifnum1>>31==0elsenum1-4294967296

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp