11/6 <bit manipulation>

389. Find the Difference

^ (按位异或): 参加运算的两个数,如果两个相应位为“异”(值不同),则该位结果为1,否则为0。

抵消掉相同的位,剩下的就是多余的位。

class Solution {
    public char findTheDifference(String s, String t) {
        char c = t.charAt(t.length() - 1);
        for(int i = 0; i < s.length(); i++){
            c ^= s.charAt(i);
            c ^= t.charAt(i);
        }
        return c;
    }
}

 

318. Maximum Product of Word Lengths

value[i] |= 1 << (tmp.charAt(j) - 'a');

int大小为32位,全部只有26个小写字母,每一位表示一个字母。

&(按位与) :对应位均为1时,结果位为1,否则为0

| (按位或):参加运算的两个数只要两个数中的一个为1,结果就为1

class Solution {
    public int maxProduct(String[] words) {
        if(words == null || words.length == 0)
            return 0;
        int len = words.length;
        int[] value = new int[len];
        for(int i = 0; i < len; i++){
            String tmp = words[i];
            value[i] = 0;
            for(int j = 0; j < tmp.length(); j++){
                value[i] |= 1 << (tmp.charAt(j) - 'a');
            }
        }
        int maxProduct = 0;
        for(int i = 0; i < len; i++)
            for(int j = i + 1; j < len; j++){
                if((value[i] & value[j]) == 0 && (words[i].length() * words[j].length() > maxProduct))
                    maxProduct = words[i].length() * words[j].length();
            }
        return maxProduct;
    }
}

 

posted @ 2019-11-06 18:54  阿飞哦  阅读(132)  评论(0编辑  收藏  举报