Printing given number in words format.
limitations:
the number must be within 0-9999
// Java program to print a given number in words. //This demo is implemented for the number between 0-9999 public class JavaOneWorld { static void numberToWords(char[] num) { // Get number of digits // in char array //calculate the lengthof the array int len = num.length; // Base cases //checking empty if (len == 0) { System.out.println("empty string"); return; } //checking number within 0-9999 if (len > 4) { System.out.println("Length more than 4 is not supported"); return; } String[] single_digits = new String[]{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; String[] two_digits = new String[]{ "", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; String[] tens_multiple = new String[]{ "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; String[] tens_power = new String[] { "hundred", "thousand"}; /* Just for debugging purpose */ System.out.print(String.valueOf(num)+": "); /* For single digit number */ if (len == 1) { System.out.println(single_digits[num[0] - '0']); return; } /* Iterate while num is not '\0' */ int x = 0; while (x < num.length) { /* Code for first 2 digits */ if (len >= 3) { if (num[x]-'0' != 0) { System.out.print(single_digits[num[x] - '0']+" "); System.out.print(tens_power[len - 3]+" "); // here len can be 3 or 4 } --len; } /* Code for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of "two_digits" array of strings */ if (num[x] - '0' == 1) { int sum = num[x] - '0' + num[x] - '0'; System.out.println(two_digits[sum]); return; } /* Need to explicitely handle 20 */ else if (num[x] - '0' == 2 && num[x + 1] - '0' == 0) { System.out.println("twenty"); return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { int i = (num[x] - '0'); if(i > 0) System.out.print(tens_multiple[i]+" "); else System.out.print(""); ++x; if (num[x] - '0' != 0) System.out.println(single_digits[num[x] - '0']); } } ++x; } } public static void main(String[] args) { String s1 = "123"; String s2 = "555"; String s3 = "6799"; String s4 = "59"; //toCharArray method will //change the string in //character type array numberToWords(s1.toCharArray()); numberToWords(s2.toCharArray()); numberToWords(s3.toCharArray()); numberToWords(s4.toCharArray()); } }
|
No comments:
Post a Comment