find difference
Title description: Given two strings s and t , they only contain lowercase letters.
The string t is randomly rearranged from the string s , and then a letter is added at a random position.
Please find the letters added t
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/find-the-difference/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Binary operation
XOR operation: If the two values of a and b are not the same, the XOR result is 1. If the two values of a and b are the same, the XOR result is 0. So if a and b are two identical numbers, the result of the XOR must be 0.
The specific process is as follows:
- If s is null or an empty string, it will directly return the first character of t
- Otherwise, initialize a X is 0, traversing S and T each character in turn and X for XOR operation, since a and b only one character is not the same, so the final XOR is the letter added.
public class LeetCode_380 {
public static char findTheDifference(String s, String t) {
if (s == null || s.length() == 0) {
return t.charAt(0);
}
int x = 0;
for (int i = 0; i < s.length(); i++) {
x ^= s.charAt(i);
x ^= t.charAt(i);
}
x ^= t.charAt(t.length() - 1);
return (char) x;
}
public static void main(String[] args) {
System.out.println(findTheDifference("abcd", "abcde"));
}
}
[Daily Message] Today’s results are yesterday’s sweat, and tomorrow’s success requires today’s efforts.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。