๋ฐ์ํ
371. Sum of Two Integers
Medium
Given two integers a
and b
, return the sum of the two integers without using the operators +
and -
.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = 2, b = 3
Output: 5
Constraints:
-1000 <= a, b <= 1000
๋ฌธ์ : ๋ ์ซ์ ๋ฅผ ๋ํ๊ฐ์ ๋ฆฌํดํ์์ค. ( * + , - ๊ธฐํธ ์ฌ์ฉํ ์ ์์)
์ฒ์์ ๋ํ๊ฐ์ ๋ฆฌํด๊น์ง๋ง ๋ณด๊ณ ๋ญ์? ๋๋ฌด์ฝ์๋! return a+b; ํ๋๋ฐ ๊ทธ๋ ๊ฒ ์ฌ์ธ๋ฆฌ๊ฐ์์ง..!
์ด๋ฌธ์ ์๋๋ ๋นํธ(2์ง์)์ฐ์ฐ์๋ฅผ ์ผ๋ง๋ ์ ์ดํดํ๊ณ ์๋๊ฐ ์ด๋ค.
๋นํธ ์ฐ์ฐ์
์ฐ์ฐ์ | ์๋ฏธ | ์ฌ์ฉ๋ฒ | ์์ | ์ค๋ช |
& | AND | x & y | x = 00000011 = 3 y = 00000110 = 6 x & y → 00000010 = 2 |
๋ ๋นํธ๊ฐ ๋ชจ๋ 1์ผ ๊ฒฝ์ฐ์๋ง 1 |
| | OR | x | y | x = 00000011 = 3 y = 00000110 = 6 x | y → 00000111 = 7 |
๋ ๋นํธ ์ค์์ ํ๋๋ผ๋ 1์ด๋ฉด 1 |
^ | XOR | x ^ y | x = 00000011 = 3 y = 00000110 = 6 x ^ y → 00000101 = 5 (x ^ y) ^ y → 00000011 = 3 |
๋ ๋นํธ๊ฐ ๊ฐ์ผ๋ฉด 0, ๋ค๋ฅด๋ฉด 1 |
~ | NOT | ~x | x = 00000010 = 2 ~x = 11111101 = 253 |
๊ฐ ๋นํธ๋ฅผ ๋ฐ์ , 0์ด๋ฉด 1, 1์ด๋ฉด 0 |
<< | Left Shift | x << 2 | x = 00000001 = 1 x << 2 = 00000100 = 4 |
๋นํธ๋ฅผ ์ผ์ชฝ์ผ๋ก ์ด๋ ํ๋ ์ด๋ํ ๋๋ง๋ค ๊ณฑํ๊ธฐ 2 |
>> | Right Shift | x >> 2 | x = 00000100 = 4 x >> 2 = 00000001 = 1 |
๋นํธ๋ฅผ ์ค๋ฅธ์ชฝ์ผ๋ก ์ด๋ ํ๋ ์ด๋ํ ๋๋ง๋ค ๋๋๊ธฐ 2 |
class Solution{
int getSum(int a, int b) {
while(b != 0) {
int num = a & b;
a ^= b;
b = num << 1;
}
return a;
}
}
public class GetSum {
public static void main(String[]args) {
// ํ
์คํธ ์ฝ๋์
๋๋ค.
Solution test = new Solution();
System.out.println(test.getSum(3,6));
}
}
[RESULT]
9
[์ค๋ช
]
1๋ฒ์งธ ๋ฐ๋ณต๋ฌธ
a : 3 [2์ง์] 00000011
b : 6 [2์ง์] 00000110
1๋ฒ์งธ a^b :5
A : 5 [2์ง์] 00000101 ( ๋ ๋นํธ๊ฐ ๊ฐ์ผ๋ฉด 0, ๋ค๋ฅด๋ฉด 1)
1๋ฒ์งธ (a&b)<<1 :4
B : 4 [2์ง์] 00000100
(๋ ๋นํธ๊ฐ ๋ชจ๋ 1์ผ ๊ฒฝ์ฐ์๋ง 1 , ๋นํธ๋ฅผ ์ผ์ชฝ์ผ๋ก 1์นธ์ด๋ )
์ฌ๊ธฐ์ a๋ 3, b๋ 6์ผ๋ก (a&b) = 00000010 , << 1 = 00000100 = 4 ๊ฐ ๋๋ค.
์๋์ ๋ฐ๋ณต๋ฌธ๋ ๊ณผ์ ์ด ๋๊ฐ๋ค.
2๋ฒ์งธ ๋ฐ๋ณต๋ฌธ
a : 5 [2์ง์] 00000101
b : 4 [2์ง์] 00000100
2๋ฒ์งธ a^b :1
A : 1 [2์ง์] 00000001
2๋ฒ์งธ (a&b)<<1 :8
B : 8 [2์ง์] 00001000
3๋ฒ์งธ ๋ฐ๋ณต๋ฌธ
a : 1 [2์ง์] 00000001
b : 8 [2์ง์] 00001000
3๋ฒ์งธ a^b :9
A : 9 [2์ง์] 00001001 <- ๋ฆฌํด๊ฐ 9 (b ๊ฐ 0์ด๋๋ฉด ๋ฐ๋ณต๋ฌธ์ด ์ข
๋ฃ๋๊ณ a์ ๊ฐ์ด ๋ฆฌํด๋๋ค. )
3๋ฒ์งธ (a&b)<<1 :0
B : 0 [2์ง์] 00000000
LeetCode ๊ณ ์๋(prashant404)์ ํ์คํ์ด๐๐ป ์์ฐ..
class Solution{
int getSum(int a, int b) {
return (b==0)?a:getSum(a^b, (a&b) << 1);
}
}
300x250
'Algorithm > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] Algorithm I - Day 2 Two Pointers (0) | 2022.10.26 |
---|---|
[LeetCode] Algorithm I - Day 1 Binary Search (0) | 2022.10.26 |
[LeetCode] 35. Search Insert Position (0) | 2022.04.20 |
[LeetCode] 3. Longest Substring Without Repeating Characters (0) | 2022.04.18 |
[LeetCode] 58. Length of Last Word (0) | 2022.04.17 |