Convert a sentence given in a string into its equivalent mobile numeric keypad sequence

 Given a sentence in the form of a string in uppercase, convert it into its equivalent mobile numeric keypad sequence.



example 1:

Input : HELLO WORLD

Output : 4433555555666096667775553




method:

For each character, store the sequence which should be obtained at its respective position in an array, i.e. for Z, store 9999. For Y, store 999. For K, store 55 and so on.

For each character, subtract ASCII value of ‘A’ and obtain the position in the array pointed

by that character and add the sequence stored in that array to a string.

If the character is a space, store 0

Print the overall sequence.



c++ implementation:

#include <bits/stdc++.h>
using namespace std;

int main() {
  int t; cin>>t;
    while(t--) 
    {
        string s;cin>>s;
        
        int n=s.length();
        string a[26]=
     {
        "2","22","222","3","33","333","4","44","444","5","55","555","6","66","666",
     
         "7","77","777","7777","8","88","888","9","99","999","9999"
     };
        
       string output = ""; 
  
   
    for (int i=0; i<n; i++) 
    { 
        // Checking for space 
        if (s[i] ==' ') 
            output = output + '0'; 
  
        else
        { 
            // Calculating index for each  
            // character 
            int position = s[i]-'A'; 
            output = output + a[position]; 
        } 
    } 
  
    // Output sequence 
    cout<<output<<endl; 
    }
    return 0;
}
Time Complexity: O(n)  ,where n is the length of the string

No comments

darkmode