Hackerrank Coding Solution

HackerRank Hiring SDE Intern

Exam Pattern:
Coding Question: 1
Exam Duration: 60 mins

Eligibility Criteria:
1)Any Graduate can apply.
Internship Duration: 6 months

Apply Link:  Click Here


Coding Question:
Phone number:
When we share our phone numbers with others, we share the numbers digit by digit.
Given a phone number in words, convert the number to digits.
For example, convert “Six four eight three to “6483”.
1. All phone numbers will be 10 digits.
2. Two repeating digits will be shortened using the word “double”. Three repeating digits will be shortened using the word “triple”. If the digits repeat four or more times, they will be shortened using “double” and “triple” multiple times.
3. The input will be always valid. For example, we won’t have a scenario like “double double two”. It will be “double two double two”
4. The entire input will be in lowercase.
Example 1
Input:
two one nine six eight one six four six zero
Output:
2196816460

Note:
Remove Everything in compiler, keep empty compiler and Type below python or java code.

Coding Solution:

Python 3:

def getPhoneNumber(s):
    d={'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9}
    res=''
    t=s.split()
    i=0
    while(i<len(t)):
        if t[i]!='double' and t[i]!='triple':
            res+=str(d[t[i]])
        else:
            if t[i]=='double':
                y=str(d[t[i+1]])*2
            else:
                y=str(d[t[i+1]])*3
            i+=1
            res+=y
        i+=1
    return res

n=input()
print(getPhoneNumber(n))

Java:

import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        System.out.println(getPhoneNumber(input));
    }

    public static String getPhoneNumber(String s) {
        HashMap<String, Integer> d = new HashMap<>();
        d.put("zero", 0);
        d.put("one", 1);
        d.put("two", 2);
        d.put("three", 3);
        d.put("four", 4);
        d.put("five", 5);
        d.put("six", 6);
        d.put("seven", 7);
        d.put("eight", 8);
        d.put("nine", 9);

        StringBuilder res = new StringBuilder();
        String[] t = s.split(" ");
        int i = 0;
        while (i < t.length) {
            if (!t[i].equals("double") && !t[i].equals("triple")) {
                res.append(d.get(t[i]));
            } else {
                String y;
                if (t[i].equals("double")) {
                    y = String.valueOf(d.get(t[i + 1])).repeat(2);
                } else {
                    y = String.valueOf(d.get(t[i + 1])).repeat(3);
                }
                i++;
                res.append(y);
            }
            i++;
        }
        return res.toString();
    }
}

Post a Comment

Previous Post Next Post

Contact Form