Programming Riddle: How might you translate an Excel column name to a number?

前端 未结 28 1117
[愿得一人]
[愿得一人] 2020-11-29 22:26

I was recently asked in a job interview to resolve a programming puzzle that I thought it would be interesting to share. It\'s about translating Excel column letters to actu

相关标签:
28条回答
  • 2020-11-29 22:58

    You can do this in C like this:

    unsigned int coltonum(char * string)
    {
       unsigned result = 0;
       char ch;
    
       while(ch = *string++)
          result = result * 26 + ch - 'A' + 1;
    
      return result;
    }
    

    No error checking, only works for upper case strings, string must be null terminated.

    0 讨论(0)
  • 2020-11-29 22:58

    Here is another version of this code in Python:

    keycode=1
    for i in range (1,len(word)):
        numtest[i]=word[i-1]
        keycode = keycode*26*int(wordtest[numtest[i]])
    last=word[-1:]
    keycode=keycode+int(wordtest[last])
    print(keycode)
    print(bin(keycode))
    #Numtest and wordtest are dictionaries.
    
    0 讨论(0)
  • 2020-11-29 22:59

    I wrote this ages ago for some Python script:

    def index_to_int(index):
        s = 0
        pow = 1
        for letter in index[::-1]:
            d = int(letter,36) - 9
            s += pow * d
            pow *= 26
        # excel starts column numeration from 1
        return s
    
    0 讨论(0)
  • 2020-11-29 23:00

    Read a column name from STDIN and print out its corresponding number:

    perl -le '$x = $x * 26 - 64 + ord for <> =~ /./g; print $x'
    

    Caveats: Assumes ASCII.

    EDIT: Replaced " with ' so that your shell won't interpolate $x in the string.

    0 讨论(0)
  • 2020-11-29 23:00

    Another Delphi one:

    function ExcelColumnNumberToLetter(col: Integer): string;
    begin
      if (col <= 26) then begin
        Result := Chr(col + 64);
      end
      else begin
        col := col-1;
        Result := ExcelColumnNumberToLetter(col div 26) + ExcelColumnNumberToLetter((col mod 26) + 1);
      end;
    end;
    
    0 讨论(0)
  • 2020-11-29 23:00

    Delphi:

    // convert EXcel column name to column number 1..256
    // case-sensitive; returns 0 for illegal column name
    function cmColmAlfaToNumb( const qSRC : string ) : integer;
    var II : integer;
    begin
       result := 0;
       for II := 1 to length(qSRC) do begin
          if (qSRC[II]<'A')or(qSRC[II]>'Z') then begin
             result := 0;
             exit;
          end;
          result := result*26+ord(qSRC[II])-ord('A')+1;
       end;
       if result>256 then result := 0;
    end;
    

    -Al.

    0 讨论(0)
提交回复
热议问题