Skip to content

Commit aca55c4

Browse files
committed
add solution : 371. Sum of Two Integers
1 parent 9870def commit aca55c4

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

โ€Žsum-of-two-integers/mmyeon.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
*@link https://leetcode.com/problems/sum-of-two-integers/description/
3+
*
4+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
5+
* - ๋น„ํŠธ AND ์—ฐ์‚ฐ์ž(&) ์‚ฌ์šฉํ•ด์„œ ์ž๋ฆฌ ์˜ฌ๋ฆผ์ด ํ•„์š”ํ•œ ๋น„ํŠธ ๊ณ„์‚ฐํ•˜๊ณ  ์™ผ์ชฝ ์‹œํŠธํŠธ๋กœ ์ž๋ฆฌ ์˜ฌ๋ฆผ๊ฐ’์„ ๋‹ค์Œ ์ž๋ฆฌ๋กœ ์ด๋™
6+
* - ๋น„ํŠธ XOR ์—ฐ์‚ฐ์ž(^) ์‚ฌ์šฉํ•ด์„œ ์ž๋ฆฌ ์˜ฌ๋ฆผ ์ œ์™ธํ•œ ์ž๋ฆฌํ•ฉ ๊ณ„์‚ฐํ•˜๊ณ  a๊ฐ’ ์—…๋ฐ์ดํŠธ
7+
* - ์ž๋ฆฌ ์˜ฌ๋ฆผ๊ฐ’์ด 0์ด ๋  ๋•Œ๊นŒ์ง€ ์ž๋ฆฌ ์˜ฌ๋ฆผ ๋ฐ˜๋ณต
8+
* - ์ž๋ฆฌ ์˜ฌ๋ฆผ ์—†์œผ๋ฉด ์ตœ์ข…ํ•ฉ์ด ์ €์žฅ๋œ a ๋ฆฌํ„ด
9+
*
10+
*
11+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(k)
12+
* - k๋Š” ์ˆซ์ž์˜ ๋น„ํŠธ ์ˆ˜, ์ตœ๋Œ€ k๋ฒˆ ๋ฐ˜๋ณต
13+
*
14+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(1)
15+
* - ๊ณ ์ •๋œ ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉ
16+
*
17+
*/
18+
19+
function getSum(a: number, b: number): number {
20+
while (b) {
21+
// ์ž๋ฆฌ ์˜ฌ๋ฆผ ๊ณ„์‚ฐ
22+
const carry = (a & b) << 1;
23+
// ์ž๋ฆฌํ•ฉ ์—…๋ฐ์ดํŠธ (๊ฐ™์€ ๋น„ํŠธ = 0, ๋‹ค๋ฅธ ๋น„ํŠธ = 1)
24+
a ^= b;
25+
b = carry;
26+
}
27+
28+
return a;
29+
}

0 commit comments

Comments
ย (0)