[英]Bitwise operator doesn't work as it supposed to in C++
我正在嘗試查找特定的字符串是否具有所有唯一字符。 我的方法是這樣的,我要初始化一個64位的變量,將其放置並設置為0。現在,我遍歷字符串並計算當前字符和“ A”(最小ASCII)之間的ASCII碼差。可能)。 如果已經設置了(places&(1“ <<” pos)),則該字符串沒有唯一字符。
一切正常,但只有小寫字符。 當我以大寫字母添加測試時,代碼不再起作用。 我確定我的可變位置有問題,但是我不知道到底是什么問題。
這是相同的代碼:
#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位int,因此當您使用小寫字母時,您會超出范圍。 顯而易見的解決方案是長期使用類常量- 1L
甚至更好的無符號長1UL
。 您也可以使用強制轉換:
static_cast<uint64_t>(1) << pos
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.