按位运算符在 C++ 中无法正常工作
Bitwise operator doesn't work as it supposed to in C++
我正在尝试查找特定字符串中是否包含所有唯一字符。我的方法是这样的,我正在初始化一个 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;
}
在 C++ 中常量有类型,在你的情况下 1 有类型 int
并且你的平台似乎有 32 位整数,所以当你使用小写字母时你会超出范围。显而易见的解决方案是使用 long - 1L
或更好的 unsigned long 1UL
类型的常量。您也可以使用强制转换:
static_cast<uint64_t>(1) << pos
我正在尝试查找特定字符串中是否包含所有唯一字符。我的方法是这样的,我正在初始化一个 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;
}
在 C++ 中常量有类型,在你的情况下 1 有类型 int
并且你的平台似乎有 32 位整数,所以当你使用小写字母时你会超出范围。显而易见的解决方案是使用 long - 1L
或更好的 unsigned long 1UL
类型的常量。您也可以使用强制转换:
static_cast<uint64_t>(1) << pos