The Wayback Machine - https://web.archive.org/web/20241008162234/https://www.geeksforgeeks.org/convert-sentence-equivalent-mobile-numeric-keypad-sequence/
Open In App

Convert a sentence into its equivalent mobile numeric keypad sequence

Last Updated : 18 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Mobile-keypad

Examples : 

Input: GEEKSFORGEEKS
Output: 4333355777733366677743333557777
Explanation: For obtaining a number, we need to press a number corresponding to that character for a number of times equal to the position of the character. For example, for character E, press number 3 two times and accordingly.

Input : HELLO WORLD
Output : 4433555555666096667775553

Approach: Follow the steps given below to convert a sentence into its equivalent mobile numeric keypad sequence. 

  • 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.

Below is the implementation of above method : 

C++




// C++ implementation to convert a
// sentence into its equivalent
// mobile numeric keypad sequence
#include <bits/stdc++.h>
using namespace std;
 
// Function which computes the sequence
string printSequence(string arr[], string input)
{
    string output = "";
 
    // length of input string
    int n = input.length();
    for (int i = 0; i < n; i++) {
        // Checking for space
        if (input[i] == ' ')
            output = output + "0";
 
        else {
            // Calculating index for each
            // character
            int position = input[i] - 'A';
            output = output + arr[position];
        }
    }
 
    // Output sequence
    return output;
}
 
// Driver Code
int main()
{
    // storing the sequence in array
    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 = "GEEKSFORGEEKS";
    cout << printSequence(str, input);
    return 0;
}


Java




// Java implementation to convert a
// sentence into its equivalent
// mobile numeric keypad sequence
import java.util.*;
 
class GFG {
 
    // Function which computes the sequence
    static String printSequence(String arr[], String input)
    {
        String output = "";
 
        // length of input string
        int n = input.length();
        for (int i = 0; i < n; i++) {
            // Checking for space
            if (input.charAt(i) == ' ')
                output = output + "0";
 
            else {
                // Calculating index for each
                // character
                int position = input.charAt(i) - 'A';
                output = output + arr[position];
            }
        }
 
        // Output sequence
        return output;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // storing the sequence in array
        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 = "GEEKSFORGEEKS";
        System.out.println(printSequence(str, input));
    }
}
 
// This code is contributed by Gitanjali.


Python3




# Python3 implementation to convert
# a sentence into its equivalent
# mobile numeric keypad sequence
 
# Function which computes the
# sequence
 
 
def printSequence(arr, input):
 
    # length of input string
    n = len(input)
    output = ""
 
    for i in range(n):
 
        # checking for space
        if(input[i] == ' '):
            output = output + "0"
        else:
            # calculating index for each
            # character
            position = ord(input[i]) - ord('A')
            output = output + arr[position]
    # output sequence
    return output
 
 
# Driver code
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"]
 
input = "GEEKSFORGEEKS"
print(printSequence(str, input))
 
# This code is contributed by upendra bartwal


C#




// C# implementation to convert a
// sentence into its equivalent
// mobile numeric keypad sequence
using System;
 
class GFG {
 
    // Function which computes the sequence
    static String printSequence(string[] arr, string input)
    {
        string output = "";
 
        // length of input string
        int n = input.Length;
        for (int i = 0; i < n; i++) {
            // Checking for space
            if (input[i] == ' ')
                output = output + "0";
 
            else {
                // Calculating index for each
                // character
                int position = input[i] - 'A';
                output = output + arr[position];
            }
        }
 
        // Output sequence
        return output;
    }
 
    // Driver Code
    public static void Main()
    {
        // storing the sequence in array
        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 = "GEEKSFORGEEKS";
        Console.WriteLine(printSequence(str, input));
    }
}
 
// This code is contributed by vt_m.


Javascript




<script>
 
// Javascript implementation to convert a
// sentence into its equivalent
// mobile numeric keypad sequence
     
    // Function which computes the sequence
    function printSequence(arr,input)
    {
        let output = "";
       
        // length of input string
        let n = input.length;
        for (let i = 0; i < n; i++)
        {
            // Checking for space
            if (input[i] == ' ')
                output = output + "0".charCodeAt(0);
       
            else
            {
                // Calculating index for each
                // character
                let position = input[i].charCodeAt(0) - 'A'.charCodeAt(0);
                output = output + arr[position];
            }
        }
       
        // Output sequence
        return output;
    }
     
    // Driver Function
    let 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" ]
     
    let input = "GEEKSFORGEEKS";
    document.write(printSequence(str, input));
     
    // This code is contributed by avanitrachhadiya2155
</script>


PHP




<?php
// PHP implementation to convert a
// sentence into its equivalent
// mobile numeric keypad sequence
 
// Function which computes the sequence
function printSequence(&$arr, $input)
{
    $output = "";
 
    // length of input string
    $n = strlen($input);
    for ($i = 0; $i < $n; $i++)
    {
        // Checking for space
        if ($input[$i] == ' ')
            $output = $output + "0";
 
        else
        {
            // Calculating index for each
            // character
            $position = ord($input[$i]) - ord('A');
            $output = $output . $arr[$position];
        }
    }
 
    // Output sequence
    return $output;
}
 
// Driver Code
 
// storing the sequence in array
$str = array("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");
 
$input = "GEEKSFORGEEKS";
echo printSequence($str, $input);
 
// This code is contributed by ita_c
?>


Output

4333355777733366677743333557777

Time complexity: O(N), For traversing the string
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Convert a Mobile Numeric Keypad sequence to equivalent sentence
Given a string S of size N, consisting of digits [0 - 9] and character '.', the task is to print the string that can be obtained by pressing the mobile keypad in the given sequence. Note: '.' represents a break while typing. Below is the image to represent the characters associated with each number in the keypad. Examples: Input: S = "234"Output: A
9 min read
Mobile Numeric Keypad Problem | Set 2
Given the mobile numeric keypad. You can only press buttons that are up, left, right or down to the current button or can choose to press the same button again. Round corner buttons (i.e. * and # ) are invalid moves. Given a number N, You have to find the distinct numbers of length N you can dial by starting from any number from 0-9, under the cons
12 min read
Mobile Numeric Keypad Problem
Given the mobile numeric keypad. You can only press buttons that are up, left, right or down to the current button. You are not allowed to press bottom row corner buttons (i.e. * and # ). Given a number N, find out the number of possible numbers of the given length. Examples: For N=1, number of possible numbers would be 10 (0, 1, 2, 3, â€Ķ., 9) For N
15+ min read
Print given sentence into its equivalent ASCII form
Given a string containing words forming a sentence (belonging to the English language). The task is to output the equivalent ASCII sentence of the input sentence. ASCII (American Standard Code for Information Interchange) form of a sentence is the conversion of each of the characters of the input string and aligning them in the position of characte
4 min read
Convert the ASCII value sentence to its equivalent string
Given a string str which represents the ASCII (American Standard Code for Information Interchange) Sentence, the task is to convert this string into its equivalent character sequence. Examples: Input: str = "71101101107115" Output: Geeks 71, 101, 101, 107 are 115 are the unicode values of the characters 'G', 'e', 'e', 'k' and 's' respectively.Input
5 min read
Print all n digit patterns formed by mobile Keypad
Given a number n. we need to print all N digit patterns formed by mobile Keypad. Note: we can move up, down, left, right from any key of mobile keypad, and every pattern contains the unique key. Examples: Input : N = 3 Output : all 3 digit Pattern are : 123, 125, 145, 147 236, 214, 258, 256, 254 321, 325, 369, 365 412, 456, 452, 458, 478 and so on
11 min read
Count of distinct Numbers that can be formed by chess knight in N moves on a mobile keypad
Given an integer N and a chess knight placed in mobile keypad. The task is to count the total distinct N digit numbers which can be formed by the chess knight with N moves. As the answer can be very large give the value of answer modulo 109 + 7. Note: In each move a chess knight can move 2 units horizontally and one unit vertically or two units ver
15+ min read
Count of buttons pressed in a keypad mobile
Given a string str, the task is to count how many times the keys will be pressed in total if there is a mobile like below image to form the given string. Examples:   Input: str = "abcdef" Output: 12 1 for a, 2 for b, 3 for c, 1 for d, 2 for e and 3 for f Total = 1 + 2 + 3 + 1 + 2 + 3 = 12Input: str = "ssss" Output: 16     Approach: Use an array to
5 min read
Convert the given BCD to its equivalent Binary form
Given a BCD (Binary Coded Decimal), the task is to convert this to its equivalent Binary number. Examples: Input: 1001000 Output: 110000 Explanation: Integer value of the given BCD is 48(0100 -> 4, 1000 -> 8). (48)10 = (110000)2 Input: 1001001 Output: 110000 Approach: In order to solve this problem we need to split the given BCD number into b
6 min read
Program to convert Hexa-Decimal Number to its equivalent BCD
Given a HexaDecimal Number N, the task is to convert the number to its equivalent Binary Coded Decimal.Examples: Input: 11F Output: 0001 0001 1111 Explanation: Binary of 1 - 0001 Binary of F - 1111 Thus, Equivalent BCD is 0001 0001 1111Input: A D Output: 1010 1101 Explanation: Binary of A - 1010 Binary of D - 1101 Thus, Equivalent BCD is 1010 1101
10 min read
Program to convert given Binary to its equivalent ASCII character string
Given a binary string str, the task is to find its equivalent ASCII (American Standard Code for Information Interchange) character string. Examples: Input: str = "0110000101100010"Output: abExplanation: Dividing str into set of 8 bits as follows: 01100001 = 97, ASCII value of 97 is 'a'.01100010 = 98, ASCII value of 98 is 'b'.Therefore, the required
9 min read
Frequency of smallest character in first sentence less than that of second sentence
Given two array of strings, arr1[] and arr2[], the task is to count the number of strings in arr2[] whose frequency of the smallest characters is less than the frequency of the smallest character for each string in arr1[]. Examples: Input: arr1[] = {"cbd"}, arr2[] = {"zaaaz"} Output: 1 Explanation: The frequency of the smallest characters in "cbd"
15 min read
Check if level-wise Decimal equivalent of Binary Tree forms a Monotonic sequence or not
Given the root of a binary tree in which all nodes has values either 0 or 1, the task is to check if the level-wise decimal equivalent of given Tree forms a monotonic sequence.or not. A sequence is monotonic if it is either monotone increasing or monotone decreasing. A sequence nums is monotone increasing if for all i <= j, nums[i] <= nums[j]
15+ min read
Check whether the string can be printed using same row of qwerty keypad
Given a string S, the task is to check whether the string can be typed using only a single row of the qwerty keyboard. Examples: Input: S = "Dad" Output: Yes Explanation: Characters "D" and "a" are present in the same row of qwerty keypad. That is second Row. Input: S = "Mom" Output: No Explanation: Characters "M" and "o" are not present in the sam
8 min read
Decimal Equivalent of Gray Code and its Inverse
Given a decimal number n. Find the gray code of this number in decimal form. Examples: Input : 7 Output : 4 Explanation: 7 is represented as 111 in binary form. The equivalent gray code of 111 is 100 in binary form, whose decimal equivalent is 4. Input : 10 Output : 15 Explanation: 10 is represented as 1010 in binary form. The equivalent gray code
7 min read
Convert an unbalanced bracket sequence to a balanced sequence
Given an unbalanced bracket sequence of '(' and ')', convert it into a balanced sequence by adding the minimum number of '(' at the beginning of the string and ')' at the end of the string. Examples: Input: str = ")))()" Output: "((()))()" Input: str = "())())(())())" Output: "(((())())(())())" Method 1: Approach: Initialize an empty stack.Iterate
13 min read
Convert given Float value to equivalent Fraction
Given a floating-point number in the form of a string N, the task is to convert the given floating-point number into fractions. Enclosed sequence of digits in "()" in the floating-point representation expresses recurrence in the decimal representation. For example, 1.(6) represents 1.666.... Examples: Input: N = "1.5"Output: 3 / 2Explanation:The va
11 min read
Program to convert polar co-ordinates to equivalent cartesian co-ordinates
Given two integers r and [Tex]\theta[/Tex](in degree) representing polar coordinates of a point (r, [Tex]\theta[/Tex]), the task is to find the Cartesian coordinates of the given point. Examples: Input: r = 1.4142, [Tex]\theta[/Tex] = 45Output: 1.000, 1.000 Input: r = 3, [Tex]\theta[/Tex] = 30Output: 2.598, 1.500 Approach: Let the cartesian coordin
4 min read
Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset
Given an array arr[] of size N and a positive integer K, the task is to find the minimum possible cost to split the array into K subsets, where the cost of ith element ( 1-based indexing ) of each subset is equal to the product of that element and i. Examples: Input: arr[] = { 2, 3, 4, 1 }, K = 3 Output: 11 Explanation: Split the array arr[] into K
7 min read
Convert String into Binary Sequence
Given a string of character the task is to convert each character of a string into the equivalent binary number. Examples : Input : GFG Output : 1000111 1000110 1000111 Input : geeks Output : 1100111 1100101 1100101 1101011 1110011 The idea is to first calculate the length of the string as n and then run a loop n times. In each iteration store ASCI
5 min read
Minimum number of operations to convert a given sequence into a Geometric Progression
Given a sequence of N elements, only three operations can be performed on any element at most one time. The operations are: Add one to the element.Subtract one from the element.Leave the element unchanged. Perform any one of the operations on all elements in the array. The task is to find the minimum number of operations(addition and subtraction) t
14 min read
Minimum increments or decrements required to convert a sorted array into a power sequence
Given a sorted array arr[] consisting of N positive integers, the task is to minimize the total number of increments or decrements of each array element required to convert the given array into a power sequence of any arbitrary integer X. A sequence is called a power sequence of any integer X, if and only if for every ith element (0 ? i < N), ar
8 min read
Minimum number of operations to convert a given sequence into a Geometric Progression | Set 2
Given an array arr[] consisting of N integers, the following three operations can be performed on any element one at a time: Add one to the element.Subtract one from the element.Leave the element unchanged.The task is to find the minimum cost required to convert it into a Geometric Progression and also find the common ratio. Note: Each addition and
13 min read
Encoding a sentence into Pig Latin
Design a program to take a sentence as an input, and then encode it into Pig Latin. A Pig Latin is an encrypted word in English, generated by placing the first letter of each word at the end, and then adding "ay" to the end. Examples: Input: s = "nevermind youve got them"Output: "evermindnay ouveyay otgay hemtay" Input: s = "sally knows best"Output
4 min read
Check if a numeric string can be split into substrings having difference between consecutive numbers equal to K
Given a numeric string S consisting of N digits and a positive integer K, the task is to check if the given string can be split into more than one substrings with difference between consecutive substrings equal to K. Examples: Input: S = "8642", K = 2Output: YesExplanation: Split the given string as {"8", "6", "4", "2"}. Now, the difference between
6 min read
Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation
Given a string S consisting of N digits, the task is to partition the string into at most two increasing subsequences such that concatenation of them also forms an increasing string. If it is not possible to do so, then print "-1". Examples: Input: S = “040425524644”Output: 0022444 44556Explanation:One of the possible way to partition the given str
10 min read
Minimum number of adjacent swaps to convert a string into its given anagram
Given two strings s1 and s2, the task is to find the minimum number of steps required to convert s1 into s2. The only operation allowed is to swap adjacent elements in the first string. Every swap is counted as a single step.Examples: Input: s1 = "abcd", s2 = "cdab" Output: 4 Swap 2nd and 3rd element, abcd => acbd Swap 1st and 2nd element, acbd
8 min read
Convert given Array of Strings to a Camel Case format sentence
Given an array arr[] of N strings, each containing words with upper or lower case English alphabets, the task is to create a sentence in a Camel Case format using them. Example: Input: arr[] = {"AnNiruddHA Routh", "LOVES", "to", "COdE everyDAY""}Output: AniruddhaRouth Loves To Code EverydayExplanation: The above sentence is the merged sentence of a
7 min read
Convert numeric words to numbers
Given a string S, containing numeric words, the task is to convert the given string to the actual number. Example: Input: S = "zero four zero one"Output: 0401 Input: S = "four zero one four"Output: 4014 Method #1: Using loop + join() + split() One of the ways to solve this problem is to use a map, where one can map the numeric with words and then s
6 min read
Minimum operations required to transform a sequence of numbers to a sequence where a[i]=a[i+2]
Given a sequence of integers of even length 'n', the task is to find the minimum number of operations required to convert the sequence to follow the rule a[i]=a[i+2] where 'i' is the index. The operation here is to replace any element of the sequence with any element. Examples: Input : n=4 ; Array : 3, 1, 3, 2 Output : 1 If we change the last eleme
11 min read
Article Tags :
Practice Tags :