Find Difference
Example
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.Note
Code
Last updated
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.Last updated
public char findTheDifference(String s, String t) {
// Convert to arrays for easy access
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();
// Initially, char code is the last t character, since that won't be included in the loop
int charCode = tChars[tChars.length - 1];
// For all positions (except the "bonus" one handled above), change running char total
for (int i = 0; i < s.length(); i++) {
charCode -= (int)sChars[i];
charCode += (int)tChars[i];
}
// Leftover amount is the value of bonus letter
return (char)charCode;
}class Solution {
public char findTheDifference(String s, String t) {
char res = t.charAt(t.length() - 1);
for (int i = 0; i < s.length(); i++) {
res ^= t.charAt(i);
res ^= s.charAt(i);
}
return res;
}
}