位操作AND [英] bit operation AND

查看:152
本文介绍了位操作AND的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个leetcode问题。
给定一个数字nums的数组,其中恰好两个元素只出现一次,所有其他元素出现正好两次。找到只出现一次的两个元素。



例如:
给定nums = [1,2,1,3,2,5] 3,5]。
我的代码是:

  class解决方案{
public:
vector< int& singleNumber(vector< int>#){
int axorb = 0;
for(auto i:nums)axorb = axorb ^ i;
int differebit =(axorb&(axorb-1))^ axorb;
int group3 = 0,group5 = 0;
for(auto i:nums)




if(differencesbit& i!= 0)group5 = group5 ^ i;




  else group3 = group3 ^ i; 
return vector< int> {group3,group5};

}
};

提交结果是错误的答案。

 输入:[0,0,1,2] 
输出:[3,0]
预期:[1,2]

但如果我只是将突出显示的部分改为

  if(differencesbit& i)group5 = group5 ^ i; 


我花了很多时间思考,但仍然不知道。也许一些类型转换发生?感谢

解决方案

这与运算符优先级有关。

因为在早期C,&&



这个

显示!= 的优先级高于 ;



可以看到 bitwise& 低于!= ,所以你的代码是这样做的:

  if(differencesbit&(i!= 0))

而不是我假设你打算做:

  if((differbit& i)!= 0)
pre>

It is a leetcode problem. 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]. My code is:

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int axorb=0;
    for(auto i:nums) axorb=axorb^i;
    int differbit=(axorb&(axorb-1))^axorb;
    int group3=0, group5=0;
    for(auto i:nums)

if(differbit&i!=0) group5=group5^i;

        else group3=group3^i;
        return vector<int>{group3,group5};

}
};

submission result is wrong answer.

Input:[0,0,1,2]
Output:[3,0]
Expected:[1,2]

But if I just change highlighted part to

if(differbit&i) group5=group5^i;

it is accepted. I spent a lot of time thinking about but still have no idea. Maybe some type conversion happened? Thanks

解决方案

This has to do with operator precedence.
Because in early C the && and || operators were added late it was given a very low priority so it wouldn't break legacy programs.

This Stack overflow Question has a very good answer as to why:

From this forum: http://bytes.com/topic/c/answers/167377-operator-precedence

The && and || operators were added later for their "short-circuiting" behavior. Dennis Ritchie admits in retrospect that the precedence of the bitwise operators should have been changed when the logical operators were added. But with several hundred kilobytes of C source code in existence at that point and an installed base of three computers, Dennis thought it would be too big of a change in the C language...


Here is A Table showing operator precedence.
Showing != at a higher priority than &.

As you can see bitwise & is lower than != on the table, so what your code is doing is the following:

if ( differbit & (i!=0) )

instead of what I assume you meant to do:

if ( (differbit & i) != 0 )

这篇关于位操作AND的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆