EXCEL SHEET COLUMN TITLE | CLEAN CODE | RUBY | INTERVIEW | | LEETCODE

By: Saurav

2018-03-31 10:23:00 UTC

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB

This problem is like that problem where we use modulo and carry. Just like add one to a number in an array format, add two binary numbers etc. the only difference is that there we dealt with 10 and 2 and here we deal with 26.

The algorithm is similar to the other ones:
While we are not done:
use number/26 for that place
use number%26 for the next one

The only deviation here is that we use the carry in the next step (not add it) and at each step, we convert the result of first operation to an alphabet

Let's see the code:

def convert_to_title(n)
    str = ''
    
    while n > 0
      str = ((n-1)%26 + 65).chr + str
      n = (n-1)/26
    end
    return str
end

The reverse program would be like:

def title_to_number(s)
    total = 0 
    i = 0 
    
    while s.length > 0 
      chr = s[-1].ord - 65 + 1 
      total += chr*26**i 
      i += 1 
      s = s[0..-2]
    end 
    
    return total
end


Let me know what you think!
twitter: sprakash24oct
linkedin

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)