[Leetcode] 1009. Complement of Base 10 Integer (C++)

마이구미·2022년 1월 4일
0

PS

목록 보기
65/69

문제

1009. Complement of Base 10 Integer

코드

class Solution {
public:
    int bitwiseComplement(int n) {
        string s = "";
        
        if (n == 0) return 1;
        
        while (n){
            s += (n%2 == 1) ? '0' : '1';
            n /= 2;
        }
        
        int res = 0, power = 0;
        while (s != ""){
            res += pow(2, power) * (s[0]-'0');
            power++;
            s = s.substr(1);
        }
        return res;
    }
};

--------------------------------------------------

class Solution {
public:
    int bitwiseComplement(int N) {
        int c = 1;
        while(c<N) c = (c << 1) + 1;
        return c^N;
    }
};

접근

단순하게 직접 2진수로 바꾸고 이를 다시 10진수로 바꾸는 과정을 구현하였다. 어려움은 딱히 없었지만 디스커션에서 발견한 두번째 코드가 신박하여 가져와 보았다. 구현한 것처럼 직접 2진수를 complement 하는 것이 아닌 1로만 구성된 같은 길이의 2진수를 만들어 xor 연산을 실행한 것이다. 1을 0으로, 0을 1로 바꾸는 것이니 xor을 떠올렸다면 떠올렸을 만한 풀이라고 생각한다.

profile
마이구미 마시쪙

0개의 댓글