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*/
        }
    }
}

No comments:

Post a Comment