Strings: Convert a string into its mobile numeric keypad

Problem Statement:

You are given a string, you need to convert that string into its equivalent mobile numeric keypad sequence.

Example

Convert a string into its mobile numeric keypad

Input : HELLO WORLD

Output : 4433555555666096667775553

Solution

The solution is very simple.

For each character, we will store the sequence of that number in an array.

Then for every character subtract ASCII value of ‘A’ and get the position in the array,

For space the character is 0

Solution in C++

#include <vector>    
#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <string>
#include <stack>

using namespace std;


string get_sequence(string arr[], 
                       string input) 
{ 
    string output = ""; 
  
    int n = input.length(); 
    for (int i=0; i<n; i++) 
    { 
        if (input[i] == ' ') 
            output = output + "0"; 
  
        else
        { 
            int pos = input[i]-'A'; 
            output = output + arr[pos]; 
        } 
    } 
  
    return output; 
} 
  
int main() 
{ 
    string str[] = {"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 input = "HELLO WORLD"; 
    cout << "The sequence is "<< get_sequence(str, input)<<endl; 
    return 0; 
} 

Output:

The sequence is 4433555555666096667775553

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *