Today I soled the "Sum of Two Integers"
Description:
This question ask us how to get sum of the two integers without using sign "+" and "-."
In example 2,
a is 2 => 10
b is 3 => 11
a+b:
10
+ 11
-----
101 (which is 5)
In binary number, 1 + 1 makes the carry "1" to the next slot.
For carry "1", we are gonna use &
a & b:
10
& 11
-----
100(so move to left <<) then 100
a XOR b:
10
^ 11
-----
01
Now see the result,
100
^ 01
-----
101 (which is "5")
Solution:
In Python, we need to constraints the bit range, because it uses large range of value.
shorter_bit = 0xffffffff shorten the value as 32-bits.
while b is more than 0, (b could be negative integer!) we XOR carry and value.
Within the loop, we know we have a carry and a XOR b.
We are gonna XOR again to a XOR b with carry.
We are gonna return a, but a should be constraints if b is a negative number.
'LeetCode ๐๏ธ > Binary' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
190. Reverse Bits (0) | 2023.05.24 |
---|---|
268. Missing Number (0) | 2023.05.23 |
338. Counting Bits (0) | 2023.05.22 |
191. Number of 1 Bits (0) | 2023.05.08 |