HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Number to words in left to right direction

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
leftnumberdirectionwordsright

Problem

I have faced this question in an interview:

If we enter a number it will convert into individual strings and display in same order.

Ex: If I enter 564 then the output should be FIVE SIX FOUR.

I have written the following working code (of course it has some limitations). Suggest any possible ways of optimizing this code.

public class NoToWord {

    public static void main(String[] a)
    {
        int no = 0;
        String[] words= new String[]{"ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE"};
        String[] word=new String[10];

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            no = Integer.parseInt(br.readLine());
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int i,j;
        j=0;
        while(no>0){
            i = no%10;
            no /= 10;
            word[j] = words[i];
            j++;
        }
        for(int k= word.length;k>0;k--)
        {
            System.out.println(word[k-1]+" ");
        }
    }
}

Solution

This code:

int i,j;
j=0;
while(no>0){
    i = no%10;
    no /= 10;
    word[j] = words[i];
    j++;
}
for(int k= word.length;k>0;k--)
{
    System.out.println(word[k-1]+" ");
}


can be drastically simplified to:

String numbers = String.valueOf(no);
for(int i = 0 ;i<numbers.length(); i++){
    System.out.print(words[Character.getNumericValue(numbers.charAt(i))]+" ");
}


Or you may save save the user input as String (but make sure it only contains digits). You will have something like this:

String numbers = br.readLine();
 for(int i = 0 ;i<numbers.length(); i++){
    System.out.print(words[Character.getNumericValue(numbers.charAt(i))]+" ");
}

Code Snippets

int i,j;
j=0;
while(no>0){
    i = no%10;
    no /= 10;
    word[j] = words[i];
    j++;
}
for(int k= word.length;k>0;k--)
{
    System.out.println(word[k-1]+" ");
}
String numbers = String.valueOf(no);
for(int i = 0 ;i<numbers.length(); i++){
    System.out.print(words[Character.getNumericValue(numbers.charAt(i))]+" ");
}
String numbers = br.readLine();
 for(int i = 0 ;i<numbers.length(); i++){
    System.out.print(words[Character.getNumericValue(numbers.charAt(i))]+" ");
}

Context

StackExchange Code Review Q#51475, answer score: 9

Revisions (0)

No revisions yet.