Java>>运算符查找字符是否唯一 [英] Java >> operator find if characters are unique
问题描述
我不太清楚这段代码是如何工作的:
I am not really sure how this code works:
public static boolean isUniqueChar2(String str) {
int checker = 0;
for (int i = 0; i < str.length(); ++i) {
int val = str.charAt(i) - 'a';
System.out.println(str.charAt(i) );
System.out.println(val);
if ((checker & (1 << val)) > 0)
return false;
checker |= (1 << val);
}
return true;
}
特别是我不明白>> operator和checker的作用
In particular I do not understand particular >> operator and the role of checker
推荐答案
看起来这种方法只适用于小写字母。 checker
变量是一个初始化为所有 0
的32位位图。代码 1<< val
取1并将其移动到 val
的位置,其代表字母表的字母(a = 0,b = 1,c = 2等)。 if((checker&(1<< val))> 0)
返回 false
除0以外,表示已重复了一封信。循环中的最后一行 checker | =(1 <; val); 设置位置
val
在下一次迭代之前。
It looks like this method is only designed to work for lower-case letters. The checker
variable is a 32-bit bitmap initialized to all 0
s. The code 1 << val
takes a 1 and shifts it into the position of val
, which represents a letter of the alphabet (a=0, b=1, c=2, etc.). if ((checker & (1 << val)) > 0)
returns false
because any value other than 0 would indicate that a letter had been repeated. The last line in the loop, checker |= (1 << val);
sets the bit at position val
before the next iteration.
这篇关于Java>>运算符查找字符是否唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!