Tag Archives: extract digit

Converting digits of an integer into words

In this post we will be discussing a method to convert individual digits of a positive integer into words i.e. 12345 will be converted into One Two Three Four Five.

We will create a String array to store the digits and then extract one digit at a time from the integer. These extracted digits will be mapped to the corresponding string equivalent. The outline will be as follows:

class NumberSystem{
    public static String convertDigitsToWords(int n){

    }
    public static void main(String args[]){
        int a=2147483647;
        System.out.println(convertDigitsToWords(a));
    }
}

The function main is purposely kept at bare minimum so that we can focus on the core task. It’s assumed that student will replace the contents of the main function with appropriate input/output logic. We will use the String class only where absolutely required and certainly not to store the number which we want to convert to words. Students must understand that String class requires extra overhead in terms of time and memory and its usage must be kept to minimum if we are aiming for efficiency—storing number as String and extracting individual digits using charAt() must be avoided as far as possible.

We will store the integer in a temporary variable and then extract the digit by finding the modulus by 10. After extracting the digit we will remove the extracted digit by dividing the temporary integer variable by 10. The process will continue till out temporary integer variable is more than 0. After incorporating the above logic our program will be as follows:

class NumberSystem{
    public static String convertDigitsToWords(int n){
        String word[]={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
        int digit;
        String answer="";
        for(int temp=n; temp>0; temp/=10){
            digit=temp%10;
            answer=word[digit]+" "+answer;
        }
        return answer.trim();
    }
    public static void main(String args[]){
        int a=2147483647;
        System.out.println(convertDigitsToWords(a));
    }
}

The above code is pretty self-explanatory but line no. 8 and line no. 10 deserves some attention. Line no. 8 is answer=word[digit]+” “+answer and not answer=answer+ ” “+word[digit] because when are using modulus to extract the digits and the digits are being extracted in reverse order i.e. in case of 123 first 3 will be extracted, then 2 will be extracted and at last 1 will be extracted. This way there is no need to take another loop for reversing the same. In line no. 10 trim() function is used to remove one extra space added at the end of the string. Also note that the use of integer variable is superfluous and it’s used for increasing the readability of the program, we can easily remove the digit variable and change line no. 8 to answer=word[temp%10]+” “+answer.