C++
class Solution {
public:
char findTheDifference(string s, string t) {
int n = t.length();
char c = t[n-1];
for (int i = 0; i < n - 1; ++i)
{
c ^= s[i];
c ^= t[i];
}
return c;
}
};
Java
public class Solution {
public char findTheDifference(String s, String t) {
int n = t.length();
char c = t.charAt(n - 1);
for (int i = 0; i < n - 1; ++i)
{
c ^= s.charAt(i);
c ^= t.charAt(i);
}
return c;
}
}
Javascript
/**
* @param {string} s
* @param {string} t
* @return {character}
*/
var findTheDifference = function(s, t) {
var c = t.charCodeAt(t.length-1);
for(var i=0; i < s.length; i++){
c = c ^ s.charCodeAt(i) ^ t.charCodeAt(i);
}
return String.fromCharCode(c);
};
我和答案思路一样,都是位运算
但是Javascript中还要进行unicode转换,不了解,做不出
JS的 “a”.charCodeAt(0)=97,作为数字就方便位运算了
网友评论