Find The Sum – Uncommon Alphabets – Uppercase
Given two char arrays input1[] and input2[ ] which contains only upper case alphabets,
Step 1: Extract the alphabets which are present only in any one of the array.
(Uncommon alphabets)
Step 2: Get the ascii values of all the extracted alphabets.
Step 3: Calculate the sum of those ascii values, lets us call it as sum1 and calculate
single digit sum for sum1
ile keep adding the digits of sum1 until you arrive at a single digit.
Step 4: Return the single digit as output.
Note :
1. Array size ranges from 1 to 15.
2. All the array elements are upper case alphabets.
Example 1:
input1: (‘A’, ‘B’, ‘C’}
input2: (‘B’, ‘C’)
output: 65 => 6 + 5 = 11
==> 1 + 1 = 2
Answers
Program in C++:
#include<iostream>
using namespace std;
int digit_sum(int num)
{
int sum = 0;
while(num > 0)
{
sum = sum + (num % 10);
num = num / 10;
}
return sum;
}
int main()
{
int size_1, size_2;
cout<<"Enter the size of array 1 : ";
cin>>size_1;
char input1[size_1];
cout<<"\nEnter the elements in array 1 (A - Z) : "<<endl;
for(int i = 0; i < size_1; i++)
{
cin>>input1[i];
}
cout<<"\nEnter the size of array 2 : ";
cin>>size_2;
char input2[size_2];
cout<<"\nEnter the elements in array 2 (A - Z) : "<<endl;
for(int i = 0; i < size_2; i++)
{
cin>>input2[i];
}
int sum1 = 0;
for(int i = 0; i < size_1; i++)
{
int flag = 0;
for(int j = 0; j < size_2; j++)
{
if(input1[i] == input2[j])
{
flag = 1;
}
}
if(flag == 0)
{
sum1 = sum1 + input1[i];
}
}
for(int i = 0; i < size_2; i++)
{
int flag = 0;
for(int j = 0; j < size_1; j++)
{
if(input2[i] == input1[j])
{
flag = 1;
}
}
if(flag == 0)
{
sum1 = sum1 + input2[i];
}
}
int sum = 0;
while(sum1 > 9)
{
sum = digit_sum(sum1);
sum1 = sum;
}
cout<<endl<<sum;
return 0;
}
Output:
Enter the size of array 1 : 3
Enter the elements in array 1 (A - Z) :
A
B
C
Enter the size of array 2 : 2
Enter the elements in array 2 (A - Z) :
B
C
2
Answer:
#include <bits/stdc++.h>
using namespace std;
int fun1(vector<char> v1, vector<char> v2) {
unordered_map<char, int> m1, m2;
for(char c : v1) m1[c]++;
for(char c : v2) m2[c]++;
vector<char> k;
for(char c : v2) {
if(m1.find(c) == m1.end()) k.push_back(c);
}
for(char c : v1) {
if(m2.find(c) == m2.end()) k.push_back(c);
}
int sum = 0;
for(char c : k) sum += c;
int s = 0;
while(sum > 9) {
while(sum) {
s += sum % 10;
sum /= 10;
}
sum = s;
s = 0;
}
return sum;
}
int main() {
vector<char> v1 = {'G','Q','R'}, v2 = {'R','T','U'};
cout << fun1(v1, v2);
return 0;
}
Explanation: