應用 XOR 特性取出相字元或數字

  1. XOR 的特性, 相同的值 XOR 會變成 0
0^0=0
1^0=1
0^1=1
1^1=0

// code
int n = 0;
for (int i = 0; i < 10000; i++) {
    n ^= i;
}
for (int i = 0; i < 10000; i++) {
    if (i == 999) continue;
    n ^= i;
}
System.out.println(n); // print 999
  1. 應用: 兩個字串只有一個字元不同的時候, 可以用來找出該不同的字元為何.
class Solution {
    // ex. s = "abc", t="ab", then ch = 'c'

    public char findTheDifference(String s, String t) {
        char ch = 0;
        for (Character c: s.toCharArray()) {
            ch ^= c;
        }
        for (Character c: t.toCharArray()) {
            ch ^= c;
        }
        return ch;
    }
}

沒有留言:

張貼留言

Lessons Learned While Using Claude Code Skills

Recently, I started experimenting with Claude Code Skills . I first saw this YouTube video: https://www.youtube.com/watch?v=CEvIs9y1uog ...