Skip to content

Commit 7af62fc

Browse files
committed
solve: Sum of Two Integers
1 parent 5bc1455 commit 7af62fc

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

โ€Žsum-of-two-integers/KwonNayeon.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
Constraints:
3+
- -1000 <= a, b <= 1000
4+
5+
Time Complexity: O(1)
6+
7+
Space Complexity: O(1)
8+
- ์ถ”๊ฐ€ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ž…๋ ฅ๋ฐ›์€ ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉ
9+
10+
ํ’€์ด๋ฐฉ๋ฒ•:
11+
1. XOR(^)์—ฐ์‚ฐ์„ ํ†ตํ•ด ์บ๋ฆฌ๋ฅผ ์ œ์™ธํ•œ ๊ฐ ์ž๋ฆฌ์˜ ํ•ฉ์„ ๊ตฌํ•จ
12+
2. AND(&)์—ฐ์‚ฐ ํ›„ ์™ผ์ชฝ ์‹œํ”„ํŠธ(<<)๋กœ ๋‹ค์Œ ์ž๋ฆฌ๋กœ ์˜ฌ๋ผ๊ฐˆ ์บ๋ฆฌ๋ฅผ ๊ตฌํ•จ
13+
3. ์บ๋ฆฌ๊ฐ€ 0์ด ๋  ๋•Œ๊นŒ์ง€ 1-2 ๊ณผ์ •์„ ๋ฐ˜๋ณต
14+
"""
15+
# Solution 1: ์ดํ•ดํ•˜๊ธฐ ์‰ฌ์šด ๋ฒ„์ „
16+
class Solution:
17+
def getSum(self, a: int, b: int) -> int:
18+
while b:
19+
current_sum = a ^ b
20+
21+
next_carry = (a & b) << 1
22+
23+
a = current_sum
24+
b = next_carry
25+
26+
return a
27+
28+
# Solution 2: ์ตœ์ ํ™” ๋ฒ„์ „
29+
class Solution:
30+
def getSum(self, a: int, b: int) -> int:
31+
while b:
32+
a, b = a ^ b, (a & b) << 1
33+
34+
return a
35+

0 commit comments

Comments
ย (0)