Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Difference between two strings JavaScript
We are given two strings, say s and t. String t is generated by random shuffling string s and then add one more letter at a random position.
We are required to write a JavaScript function that takes both these strings and returns the letter that was added to t.
For example −
If the input stings are −
const s = "abcd", t = "abcde";
Then the output should be −
const output = "e";
because 'e' is the letter that was added.
Example
const s = "abcd", t = "abcde";
const findTheDifference = (s, t) => {
let a = 0, b = 0; let charCode, i = 0;
while(s[i]){
a ^= s.charCodeAt(i).toString(2);
b ^= t.charCodeAt(i).toString(2);
i++;
};
b^=t.charCodeAt(i).toString(2);
charCode = parseInt(a^b,2);
return String.fromCharCode(charCode);
};
console.log(findTheDifference(s, t));
Output
And the output in the console will be −
e
Advertisements
