leetcode with python: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.

给定一数,回传其在二进位表示时,0改1,1改0后的值
ex:input:5(101)=>output:2(010)

这题使用位元运算

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

先设一数i为1,不断行左移操作直到大于num
如5(101),i最后会跑到8(1000)
再回传其-1和num行^操作的结果即可(111^101=010)
最后执行时间30ms(faster than 94.48%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章