Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal number to excel-header-like number

0 = A
1 = B
...
25 = Z
26 = AA
27 = AB
...
701 = ZZ
702 = AAA

I cannot think of any solution that does not involve loop-bruteforce :-(

I expect a function/program, that accepts a decimal number and returns a string as a result.

like image 627
zerkms Avatar asked Dec 15 '10 07:12

zerkms


2 Answers

Haskell, 78 57 50 43 chars

o=map(['A'..'Z']:)$[]:o
e=(!!)$o>>=sequence

Other entries aren't counting the driver, which adds another 40 chars:

main=interact$unlines.map(e.read).lines

A new approach, using a lazy, infinite list, and the power of Monads! And besides, using sequence makes me :), using infinite lists makes me :o

like image 143
stusmith Avatar answered Sep 19 '22 15:09

stusmith


If you look carefully the excel representation is like base 26 number but not exactly same as base 26.

In Excel conversion Z + 1 = AA while in base-26 Z + 1 = BA

The algorithm is almost same as decimal to base-26 conversion with just once change. In base-26, we do a recursive call by passing it the quotient, but here we pass it quotient-1:

function decimalToExcel(num)

        // base condition of recursion.
        if num < 26
                print 'A' + num 

        else                     
                quotient = num / 26;
                reminder = num % 26;

                // recursive calls.
                decimalToExcel(quotient - 1);
                decimalToExcel(reminder);
        end-if                       
end-function 

Java Implementation

like image 45
codaddict Avatar answered Sep 21 '22 15:09

codaddict