My Java solution using stack


  • 0
    Q
    public class Solution {
        private static final String[] s1 = new String[]{"", "Thousand", "Million", "Billion"};
        private static final String[] s2 = new String[]{"", "", "Twenty", "Thirty", "Forty", "Fifty",
        		"Sixty", "Seventy", "Eighty", "Ninety"};
        private static final String[] s3 = new String[]{"", "One", "Two", "Three", "Four", "Five",
        		"Six", "Seven", "Eight", "Nine"};
        private static final String[] s4 = new String[]{"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
        		"Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
        		
        public String numberToWords(int num) {
        	if (num == 0){
        		return "Zero";
        	}
            Queue<Integer> l = new LinkedList<Integer>();
            while (num!=0){
                int d = num%10;
                l.offer(d);
                num = num/10;
            }
            int count=0;
            int level = 0; //thousand, million, billion
            Stack<String> stack = new Stack<String>();
            boolean s1Added = false;
            while (! (l.isEmpty())){
                int i = l.poll();
                
                count++;
                int next = 0;
                if (!l.isEmpty()){
                	next = l.peek();
                }
                if (count == 1 && next == 1){
                    if (level>0){
                        stack.push(s1[level]);
                    }
                	l.poll();
                	count++;
                	stack.push(s4[i]);
                	s1Added = true;
                }
                else if (count == 1 && i>0){
                    if (level>0){
                        stack.push(s1[level]);
                    }
                	stack.push(s3[i]);
                    s1Added = true;
                }
                else if (count == 2 && i>0){
                    if (!s1Added  && level>0){
                	    stack.push(s1[level]);
                	}
                	stack.push(s2[i]);
                	s1Added = true;
                }
                else if (count == 3){
                    if (i>0){
                        if (!s1Added && level>0){
                    	    stack.push(s1[level]);
                    	}
                    	stack.push("Hundred");
                		stack.push(s3[i]);
                	}
                	level++;
                	count = 0;
                	s1Added = false;
                }
            }
            
            StringBuffer sb = new StringBuffer();
            while (!stack.isEmpty()){
                String s = stack.pop();
                sb.append(s).append(" ");
            }
            return sb.toString().trim();
        }
    }

Log in to reply
 

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