- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Difference in C++
Suppose we have two strings s and t which consist of only lowercase letters. Now, string t is generated by random shuffling string s and then add one more letter at a random index. We have to find the letter that was added in t.
So, if the input is like "mnopq","pqmnot", then the output will be "t", this is the extra letter.
To solve this, we will follow these steps −
sSum := 0, tSum := 0
for initialize i := 0, when i < call length() of s, update (increase i by 1), do −
sSum := sSum + s[i]
for initialize j := 0, when j < call length() of t, update (increase j by 1), do −
tSum := tSum + t[j]
return (tSum - sSum) as character
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: char findTheDifference(string s, string t) { int sSum = 0; int tSum = 0; for (int i = 0; i < s.length(); i++) { sSum += s[i]; } for (int j = 0; j < t.length(); j++) { tSum += t[j]; } return char(tSum - sSum); } }; main(){ Solution ob; cout << (ob.findTheDifference("mnopq","pqmnot")); }
Input
"mnopq","pqmnot"
Output
t
Advertisements