本文主要是介绍Leetcode 476. Number Complement,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
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.
Algorithm
Use bit operations.
Code
class Solution:def findComplement(self, num: int) -> int:n, m = 1, numwhile m:n <<= 1m >>= 1return (n-1) & (~num)
这篇关于Leetcode 476. Number Complement的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!