Interview Question Categories

Excel column number to alpha and reverse

Excel column number to alpha and reverse


namespace ExcelColumnfromNumToAlpha
{
    class Program
    {

        static void Main(string[] args)
        {
            /*Begin : Column Number to Alphabets*/
            //Number to Alphabet, assumption : column A starts at 0. 
            // if Column A starts from 1 then 
            //subtract 1 from the input column number.
            int ColumnNum = 702;
            String ColumnAlpha = "";
            int r;

            r = ColumnNum % 26;
            ColumnAlpha = (char)(r + 65) + ColumnAlpha;
            ColumnNum = ColumnNum / 26;
                
            while (ColumnNum > 0)
            {
                r = ColumnNum % 26;
                ColumnAlpha = (char)(r + 64) + ColumnAlpha;
                ColumnNum = ColumnNum / 26;
            }
            
            Console.WriteLine(ColumnAlpha);
            /*End: Column Number to Alphabets*/





            /*Begin : Column Alphabets to number*/
            //Alphabet to number - assumption = Col num starts from 1 i.e A is 1. 
            //if it starts from 0, then subtract 1 from the final answer.
            String ColumninAlpha = "AB";
            int ColNum = 0;
            for (int i = 0; i < ColumninAlpha.Length; i++)
            {
                ColNum = ColNum * 26 + (int)(ColumninAlpha[i] - 'A') + 1;
            }
            Console.WriteLine(ColNum);
            /*End: Column Alphabets to number*/
        }
    }
}

1 comment:

  1. In your program the first time you are adding 65 is actually wrong, that should be 64. You can test this by giving "ColumninAlpha" value to "AAA" this will give you 703 as per your program but as what you have given in your first part is 702 which is resulting into "AAA" kind of a mismatch ...

    ReplyDelete