(Leetcode) [Binary]: Sum of two integers

Topic: Binary
Difficulty: Medium


๋ง์…ˆ๊ณผ ๋บ„์…ˆ ์—ฐ์‚ฐ์ž (+, -) ์‚ฌ์šฉ ์—†์ด ๋‘ ์ •์ˆ˜์˜ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ.

์ผ๋‹จ ๋‹จ์› ์ œ๋ชฉ์ด binary์—ฌ์„œ binary๋ฅผ ์ด์šฉํ•ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์€ ๋ฐ”๋กœ ์•Œ์•„์ฐจ๋ ธ๋‹ค.

My first idea

  1. ์‹ญ์ง„๋ฒ• ์ˆ˜๋ฅผ ์ด์ง„๋ฒ•์œผ๋กœ ๋ณ€๊ฒฝ.
  2. ์ด์ง„๋ฒ• ๋ง์…ˆํ•˜๊ธฐ.
  3. ์ด์ง„๋ฒ•์œผ๋กœ ์“ฐ์—ฌ์žˆ๋Š” ๋‹ต์„ ์‹ญ์ง„๋ฒ•์œผ๋กœ ๋‹ค์‹œ ๋ณ€๊ฒฝ.

๋ฌธ์ œ์ 

๋งŒ์•ฝ ๋‹ต์ด ์Œ์ˆ˜์ด๋ฉด ์Œ์ˆ˜๋ฅผ ์ ˆ๋Œ“๊ฐ’ ์”Œ์šด ์–‘์ˆ˜๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ๊ณผ์ •์ด ๊ต‰์žฅํžˆ ๋ณต์žกํ•ด์ง„๋‹ค.
์ด๊ฒŒ ๋ญ” ์†Œ๋ฆฌ๋ƒ? 2์ง„๋ฒ•์—์„œ MSB(most significant bit)๋Š” ๋ถ€ํ˜ธ๋ฅผ ๋‚˜ํƒ€๋‚ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค (2โ€™s complement).
1 for negative number, and 0 for positive number.
์Œ์ˆ˜๋ฅผ ์–‘์ˆ˜๊ฐ’์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋ ค๋ฉด ๊ฐ digit์˜ ๋ฐ˜๋Œ€๋˜๋Š” ์ˆซ์ž๋กœ ๋ฐ”๊พธ๊ณ  (0์ด๋ฉด 1๋กœ, 1์ด๋ฉด 0์œผ๋กœ) LSB (least significant bit)์— 1์„ ๋”ํ•œ๋‹ค.
์ฃผ์ €๋ฆฌ ์ฃผ์ €๋ฆฌ ์ผ์ง€๋งŒ ๊ฒฐ๋ก ์€ ์ด ๊ณผ์ •์œผ๋ก  ์ฝ”๋“œ๊ฐ€ ๊ต‰์žฅํžˆ ๊ธธ์–ด์งˆ๊ฑฐ๊ณ  ๋น„ํšจ์œจ์ ์ด๋ž€ ๊ฒƒ์ด๋‹ค.

Solution

class Solution {
public:
    int getSum(int a, int b) {
        while (b != 0) {
            unsigned carry = a&b;   // carry should be unsigned to deal with negative numbers
            a = a^b;    
            b = carry << 1;
        }
        return a;
    }
};

์ด๋ฒˆ์—” geeksforgeeks์—์„œ ๋„์›€์„ ๋ฐ›์•˜๋‹ค.
๋‹ค์„ฏ์ค„์ด๋ฉด ๋  ๊ฒƒ์„ 70์ค„์„ ์“ฐ๊ณ  ์•‰์•„์žˆ์—ˆ๋‹ค.

  1. AND operator๋ฅผ ์ด์šฉํ•ด์„œ carryin์„ ์ฐพ๋Š”๋‹ค.
  2. XOR operator๋ฅผ ์ด์šฉํ•ด์„œ ๊ฐ digit์—์„œ 0+1=1์ด๋‚˜ 1+0=1 ๊ณ„์‚ฐ์„ ํ•ด์ค€๋‹ค. 0+0์€ 0์ผํ…Œ๊ณ , 1+1์€ carryin์œผ๋กœ ๋„˜์–ด๊ฐˆํ…Œ๋‹ˆ 0์ด ๋  ๊ฒƒ์ด๋‹ค.

ํ•˜๋‹ค๊ฐ€ b (carryin)์ด 0์ด ๋˜๋ฉด ๋๋‚ธ๋‹ค.

e.g.
a=0010, b=0011

carry=0010
a=0001
b=0100

carry=0000
a=0101
b=0000

return a=0101

Categories:

Updated:

Leave a comment