按位运算符不能像在C ++中那样工作

时间:2018-09-25 18:13:13

标签: c++ bit-manipulation bit

我正在尝试查找特定字符串中是否包含所有唯一字符。我的方法是这样的,我要初始化一个64位的变量,例如 places 并将其设置为0。现在,我遍历字符串并计算当前字符和“ A”之间的ASCII码之间的差异(可能的最小ASCII码)。如果已经设置了(places&(1“ <<” pos)),则该字符串没有唯一字符。

一切正常,但只能使用小写字符。当我以大写字母添加测试时,代码不再起作用。我可以确定我的变量 places 的含义,但是我不知道到底是什么问题。

以下是同一代码:

#include <bits/stdc++.h>
using namespace std;

void check_unique(string s){
    int64_t places=0;       
    for(int i=0;i<s.length();i++){   
    int pos=s[i]-'A';            
    if((places & (1<<pos))!=0){  
        cout<<"String does not have all unique characters\n";   
        return;
    }
    places|=(1<<pos);            
  }
   cout<<"String has all unique characters\n";   
}

int main() {
    check_unique("abcde"); // Testcase 1
    check_unique("aabb");  // Testcase 2
    check_unique("ABbde");   // Testcase 3, Wrong output.
    return 0;
}

1 个答案:

答案 0 :(得分:4)

在C ++常量具有类型的情况下,在您的情况下1的类型为int,并且看来您的平台具有32位整数,因此,当您使用小写字母时,您会超出范围。明显的解决方案是使用long类型的常量-1L,甚至最好使用无符号long 1UL类型。您也可以使用演员表:

static_cast<uint64_t>(1) << pos