C++ - leetCode 476. Number Complement

2024. 8. 22. 22:35C_C++

728x90
반응형
/* leetCode 476. Number Complement

The complement of an integer is the integer you get when you flip all the 0's
to 1's and all the 1's to 0's in its binary representation.

For example, The integer 5 is "101" in binary and its complement is "010" which
is the integer 2.
Given an integer num, return its complement.

* Constraints:

1 <= num < 2^31

* Example 1:

    Input: num = 5
    Output: 2
    Explanation: The binary representation of 5 is 101 (no leading zero bits), 
                 and its complement is 010. So you need to output 2.

* Example 2:

    Input: num = 1
    Output: 0
    Explanation: The binary representation of 1 is 1 (no leading zero bits), 
                 and its complement is 0. So you need to output 0.

* 풀이

차례대로 하나의 bit 씩 반전을 시켜 주면 되는데, num 의 LSB 부터 몇 번째까지 bit 가
있는지 확인하는 것이 포인트.
*/

#include <iostream>

class Solution {
public:
	int findComplement(int num) {
        if (num == 0)
			return 1;

        // set all bits to 1
		unsigned int mask = ~0;

        // shift until num has no set bits
        while ((num & mask) != 0)
			mask <<= 1;

		return ~mask & ~num;
	}
};

int main() {
	Solution s;

	std::cout << s.findComplement(5) << std::endl;  // 2
	std::cout << s.findComplement(1) << std::endl;  // 0
	std::cout << s.findComplement(2) << std::endl;  // 1
}
728x90
반응형