Java >> operator find if characters are unique [closed]

南笙酒味 提交于 2019-12-02 19:41:10

问题


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;
}

In particular I do not understand particular >> operator and the role of checker


回答1:


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 0s. 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.




回答2:


and | are bitwise shift and binary or. I suggest you do some reading of binary and bitwise operator: http://en.wikipedia.org/wiki/Bitwise_operation

a |= b is just a shorthand of a = a | b similar like a += b to a = a + b



来源:https://stackoverflow.com/questions/13982314/java-operator-find-if-characters-are-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!