Search code examples
javaradixletters

Program to convert numbers to letters


Im trying to crate a program that does this: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD....ZZ AAA AAB AAC

The way I approached this is hard to put into words but I'll try explaining

I tried creating a base 27 system and make A represent 1, B->2 C->3, and AA->28 The problem is that every 27 letters where I get an @ representing 0.

I also tried making A represent 0 and having a base 26 system but 27 would be BA when I need it to be AA

public class aaa 
{
    public static void main(String args[]) 
{
    int counter=29;
    for(int x=0;x<=counter;x++)
    {   
        int quotient, remainder;
        String result="";
        quotient=x;

        while (quotient>0)
        {   
            remainder=quotient%27;
            result = (char)(remainder+64) + result;
            quotient = (int)Math.floor(quotient/27);

        }
    System.out.print(result+ " ");
           }
    }
}

This prints out A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A@ AA AB

I want the program to do this A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC


Solution

  • As a start, as several answers already mentioned, there are 26 letters, so use a base 26 system, not 27.

    Besides that, print A as 0, instead of @, so change (char)(remainder + 64) to (char)(remainder + 65). The last thing you need to do is change quotient = (int)Math.floor(quotient/27); because you want to print A, that will be 0 in this scale, so subtract 1 from it and stop loop when quotient smaller than 0.

    public class HelloWorld{
    
         public static void main(String []args){
            int counter=59;
            for(int x=0; x<=counter; x++)
            {   
                int quotient, remainder;
                String result="";
                quotient=x;
    
                while (quotient >= 0)
                {
                    remainder = quotient % 26;
                    result = (char)(remainder + 65) + result;
                    quotient = (int)Math.floor(quotient/26) - 1;
                }
                System.out.print(result+ " ");
            }
         }
    }
    

    Output (note that there is no space at start of output also):

    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH
    

    Ps: Indent your code correctly!