Skip to content

Commit d6cd7a4

Browse files
committed
Solution: Sum of Two Integers
1 parent f76f713 commit d6cd7a4

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

โ€Žsum-of-two-integers/flynn.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* ํ’€์ด
3+
* - ๋‘ ์ •์ˆ˜๋ฅผ ํ•œ bit์”ฉ ๋”ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ’€์ดํ•ฉ๋‹ˆ๋‹ค
4+
* - ๋‘ ์ •์ˆ˜์— ๋Œ€ํ•ด ์ด์ง„ ๋ง์…ˆ์„ ์ง„ํ–‰ํ•  ๋•Œ, ํ•ด๋‹น ์ž๋ฆฌ์ˆ˜์˜ bit ๋‘ ๊ฐœ์™€ carry๋ฅผ ๋น„๊ตํ•˜์—ฌ ์ƒˆ๋กœ์šด carry์™€ ํ•ด๋‹น ์ž๋ฆฌ์ˆ˜์˜ ๋ง์…ˆ ๊ฒฐ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค -> adder ํ•จ์ˆ˜ ์ฐธ๊ณ 
5+
* - ๊ฐ ๋น„ํŠธ์— ๋Œ€ํ•ด adder ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ๋ง์…ˆ์„ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค
6+
* - res์˜ ํŠน์ • ์ž๋ฆฌ์— ๋ง์…ˆ ๊ฒฐ๊ณผ๋ฅผ ๋„ฃ์–ด์ฃผ๋Š” ๊ฒƒ์ด ๊นŒ๋‹ค๋กœ์› ๋Š”๋ฐ, position์ด๋ผ๋Š” ์ผ์ข…์˜ bitmask๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค
7+
* - ์ €๋Š” Nand2Tetris ๋ผ๋Š” ์ฑ…/๊ฐ•์˜๋ฅผ ๋ณด๋ฉด์„œ ์ด ์ „์— bitwise ์‚ฐ์ˆ  ์—ฐ์‚ฐ๊ธฐ๋ฅผ ๊ตฌํ˜„ํ•œ ์ ์ด ์žˆ์—ˆ๋Š”๋ฐ, ๊ทธ ๊ฒฝํ—˜์ด ํฐ ๋„์›€์ด ๋˜์—ˆ์Šต๋‹ˆ๋‹ค
8+
* ๊ถ๊ธˆํ•˜์‹  ๋ถ„๋“ค๊ป˜ coursera ๊ฐ•์˜ ๋งํฌ๋ฅผ ์ฒจ๋ถ€ํ•ฉ๋‹ˆ๋‹ค (๋ฌด๋ฃŒ) (https://www.coursera.org/learn/build-a-computer) (2๊ฐ•์— ๋‚˜์˜ด)
9+
*
10+
* Big O
11+
* - N: a์™€ b ์ค‘ ํฐ ์ˆ˜์˜ ๋น„ํŠธ ์ˆ˜ <= 32 (c++ ๊ธฐ์ค€)
12+
*
13+
* - Time complexity: O(N <= 32) = O(1)
14+
* - Space complexity: O(1)
15+
*/
16+
17+
class Solution {
18+
public:
19+
// returns {carry, result}
20+
// carry์™€ result๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์€ bool ์—ฐ์‚ฐ์œผ๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์‚ฌ์‹ค์€
21+
// x, y, c์— ๋Œ€ํ•˜์—ฌ ๋ฒค ๋‹ค์ด์–ด๊ทธ๋žจ์„ ๊ทธ๋ ค๋ณด๋ฉด ์‰ฝ๊ฒŒ ํŒŒ์•…ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
22+
pair<bool, bool> adder(bool x, bool y, bool c) {
23+
return {(x & y) | (x & c) | (y & c), x ^ y ^ c};
24+
}
25+
26+
int getSum(int a, int b) {
27+
bool carry = 0;
28+
unsigned int res = 0;
29+
unsigned int position = 1;
30+
31+
// 32 ๋น„ํŠธ ์ •์ˆ˜ ๋ฒ”์œ„ ๋‚ด์—์„œ ๋ง์…ˆ์„ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค
32+
// 32 ๋น„ํŠธ ๋ชจ๋‘ ๋ง์…ˆ์„ ์ง„ํ–‰ํ–ˆ๊ฑฐ๋‚˜, ๋” ๋”ํ•  ๋น„ํŠธ๊ฐ€ ์—†๋‹ค๋ฉด ๋ฃจํ”„๋ฅผ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค
33+
while (position && (a || b || carry)) {
34+
bool lsb_a = a & 1;
35+
a >>= 1;
36+
37+
bool lsb_b = b & 1;
38+
b >>= 1;
39+
40+
auto [new_carry, new_res] = adder(lsb_a, lsb_b, carry);
41+
42+
carry = new_carry;
43+
if (new_res) res |= position;
44+
45+
// position์ด unsigned int (32๋น„ํŠธ)์ด๋ฏ€๋กœ
46+
// bitwise left shift ์—ฐ์‚ฐ์„ 32๋ฒˆ ์ˆ˜ํ–‰ํ•˜๋ฉด 0์ด ๋จ
47+
// 1000 0000 0000 0000 0000 0000 0000 0000 => 0000 0000 0000 0000 0000 0000 0000 0000
48+
// position์ด 0์ด ๋˜๋ฉด 32๋น„ํŠธ ๋ชจ๋‘ ๋ง์…ˆ์„ ์™„๋ฃŒํ–ˆ๋‹ค๋Š” ๋œป์ด๋ฏ€๋กœ loop๋ฅผ ์ข…๋ฃŒํ•จ
49+
position <<= 1;
50+
}
51+
52+
return (int) res;
53+
}
54+
};

0 commit comments

Comments
ย (0)