Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an int so as to return the string which is how we say the int

Tags:

java

string

int

I came across this interview question where the interviewer asked to write a function which will take an integer, say 123, and will return a string that would be how one would say that integer.In above case output should be "one hundred and twenty three".I have no idea how to solve these problems.Can anyone help in how to work out this problem? A pseudo code will be helpfull.

like image 213
user2916886 Avatar asked Dec 06 '25 10:12

user2916886


2 Answers

Here is the solution to your problem:

Numbers to words

It is not as simple as you may imagine.

like image 88
Anastasios Vlasopoulos Avatar answered Dec 08 '25 00:12

Anastasios Vlasopoulos


Use this Code for Converting Numbers to Word Source here

 public class YourNumberMyWord { 
        public void pw(int n,String ch) { 
            String one[]={" "," one"," two"," three"," four"," five"," " +
                    "six"," seven"," eight"," Nine"," ten"," eleven"," twelve"," " +
                            "thirteen"," fourteen","fifteen"," sixteen"," seventeen"," eighteen"," nineteen"}; 

            String ten[]={" "," "," twenty"," thirty"," forty"," fifty"," sixty","seventy"," eighty"," ninety"};   
            if(n>19) { 
                System.out.print(ten[n/10]+" "+one[n%10]);
            } 
            else { 
                System.out.print(one[n]);} if(n>0)System.out.print(ch); 
                } 

        public static void main(String[] args) {
            int n=0; Scanner scanf = new Scanner(System.in); 
            System.out.println("Enter an integer number: "); 
            n = scanf.nextInt();

            if(n<=0) 
                System.out.println("Enter numbers greater than 0"); 
            else { 
                YourNumberMyWord a = new YourNumberMyWord(); 
                a.pw((n/1000000000)," Hundred"); a.pw((n/10000000)%100," crore"); 
                a.pw(((n/100000)%100)," lakh"); a.pw(((n/1000)%100)," thousand"); 
                a.pw(((n/100)%10)," hundred"); a.pw((n%100)," "); 
            }
            }

    }
like image 24
Nambi Avatar answered Dec 08 '25 01:12

Nambi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!