Skip to content

476. Number Complement #144

@zeikar

Description

@zeikar

Problem link

https://leetcode.com/problems/number-complement/

Problem Summary

수가 주어질 때 complement를 구하는 문제.

Solution

1이 0이 되고 0이 1이 되려면?? XOR를 쓰면 된다.
자릿수를 올라가면서 1과 XOR를 하면 1은 0이 되고 0은 1이 된다.

Source Code

class Solution:
    def findComplement(self, num: int) -> int:
        b = 1
        while num >= b:
            num ^= b
            b <<= 1
        return num

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions