首页 > 其他 > 详细

位运算取第一个非0的位 r & (~(r-1))

时间:2016-10-10 01:15:38      阅读:515      评论:0      收藏:0      [点我收藏+]

Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

 

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
[1,1,2]=>1 xor 1 xor 2=2
[1, 2, 1, 3, 2, 5]=> all xor= 3 & 5 != 0 => 0x11 xor 0x101=bit 2,3 is not equal=>find bit2 and seperate like [1,1,2]
        """
        r = 0
        for num in nums:
            r = r ^ num
        assert r != 0
        n = r & (~(r-1))
        ans1, ans2 = 0, 0
        for num in nums:
            if num & n == 0:
                ans1 = ans1 ^ num
            else:
                ans2 = ans2 ^ num
        return ans1, ans2
        

 

位运算取第一个非0的位 r & (~(r-1))

原文:http://www.cnblogs.com/bonelee/p/5944192.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!