Skip to content

Commit d0237c7

Browse files
add: Sum of Two Integers
1 parent 1b3b88e commit d0237c7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
// tc -> O(1)
3+
// NOTE: μžλ°”μ˜ Integer.parseIntλŠ” 음수 ν‘œν˜„μ„ μ²˜λ¦¬ν•˜μ§€ λͺ»ν•¨.. μ–‘μ˜ λΆ€ν˜Έκ°€ μ—†λŠ” μ΄μ§„μˆ˜λ§Œ 지원. (음수의 경우 1111111~ 둜 μ‹œμž‘ν•˜λŠ” 이진 λ¬Έμžμ—΄μ„ μ–‘μˆ˜λ‘œ ν•΄μ„ν•˜λ € μ‹œλ„ν•΄ λŸ°νƒ€μž„ 였λ₯˜ λ°œμƒ)
4+
class Solution {
5+
public int getSum(int a, int b) {
6+
String aStr = String.format("%32s", Integer.toBinaryString(a)).replace(" ", "0");
7+
String bStr = String.format("%32s", Integer.toBinaryString(b)).replace(" ", "0");
8+
char[] sum = new char[32];
9+
boolean isCarry = false;
10+
11+
for (int i = sum.length - 1; i >= 0; i--) {
12+
if (aStr.charAt(i) == bStr.charAt(i) && aStr.charAt(i) == '1') {
13+
14+
sum[i] = isCarry ? '1' : '0';
15+
isCarry = true;
16+
continue;
17+
}
18+
19+
if (aStr.charAt(i) == '1' || bStr.charAt(i) == '1') {
20+
sum[i] = isCarry ? '0' : '1';
21+
isCarry = isCarry ? true : false;
22+
continue;
23+
}
24+
25+
sum[i] = isCarry ? '1' : '0';
26+
isCarry = false;
27+
}
28+
29+
String resStr = new String(sum);
30+
return (int) Long.parseLong(resStr, 2);
31+
}
32+
}

0 commit comments

Comments
Β (0)