Non Recursive Java Implementation


  • 0
    M
    public class Solution {
        String[] zeroToNineteen = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine",
    	"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    	String[] tens = {"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
    	String[] others = {"","Thousand","Million","Billion"};
    
    	public String numberToWords(int num) {
    		if(num == 0) return "Zero";
    		String s = "";
    		int count = 0;
    		while(num!=0) {
    			 String t =identifyThreeDigitNumbers(num%1000);
    			 if(!t.isEmpty()){
    				 t+= " " + others[count];
    				 s = t.trim() + " " + s;
    			 }
    			 
    			 num/=1000;
    			 count++;
    		}
    		
            return s.trim();
        }
    	
    	
    	public String identifyThreeDigitNumbers(int num) {
    		
    		int lastTwo = num%100;
    		int last = num/100;
    		String s = "";
    		if(lastTwo<20) {
    			s+= zeroToNineteen[lastTwo];
    		} else {
    			s+= tens[lastTwo/10] + " " + zeroToNineteen[lastTwo%10];
    		}
    		
    		if(last>0) {
    			s = zeroToNineteen[last] + " Hundred " + s;
    		}
    		
    		return s.trim();
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.