0

I'm not getting where my code is getting wrong even I Checked for many of the border cases

import java.util.*;
class fun
{
    String a[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    String b[] = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    String dis(int n)
    {
        String s ="";
        if(n/100>0)
            s+=a[n/100]+" Hundred ";
        if(n%100/10==0)
            s+=a[n%10];
        else if(n%100/10==1)
            s+=a[n%100];
        else
            s+=b[n%100/10]+" "+a[n%10];
        return s;
    }
}
public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt(), a, b, c, d, e;
        fun f = new fun();
        while(t-->0)
        {
            String Str="";
            long n = sc.nextLong();
            a=(int)(n/Math.pow(10,12));
            b=(int)(n/Math.pow(10,9)%1000);
            c=(int)(n/Math.pow(10,6)%1000);
            d=(int)(n/Math.pow(10,3)%1000);
            e=(int)(n%1000);
            if(a==1)
                Str = "One Trillion";
            else
            {
                if(b!=0)
                    Str+=f.dis(b)+" Billion ";
                if(c!=0)
                    Str+=f.dis(c)+" Million ";
                if(d!=0)
                    Str+=f.dis(d)+" Thousand ";
                Str+=f.dis(e);
            }
            System.out.println(Str);
        }
    }
}

If input is:
1
104382426112

then output is:
One Hundred Four Billion Three Hundred Eighty Two Million Four Hundred Twenty Six Thousand One Hundred Twelve

1 Answers1

2

The only problem I can see is that this code won't work for numbers greater than Integer.MAX_VALUE ... which is 2,147,483,647. That's 2 billion and a bit.

The reason for that limitation is that you are using int to do the integer arithmetic. Solution: use long instead.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216