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

前端 未结 28 1399
[愿得一人]
[愿得一人] 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:53

    Hah - written it already in our code base - about 3 different times :(

    %% @doc Convert an string to a decimal integer
    %% @spec b26_to_i(string()) -> integer()
    
    b26_to_i(List) when is_list(List) ->
        b26_to_i(string:to_lower(lists:reverse(List)),0,0).
    
    %% private functions
    b26_to_i([], _Power, Value) -> 
        Value;
    
    b26_to_i([H|T],Power,Value)->
        NewValue = case (H > 96) andalso (H < 123) of
                       true ->
                           round((H - 96) * math:pow(26, Power));
                       _    ->
                           exit([H | T] ++ " is not a valid base 26 number")
                   end,
        b26_to_i(T, Power + 1, NewValue + Value).
    

    The riddle is that it isn't actually a Base26 representation of a number (we are lying to ourselves in our function name here) because there is no 0 in it.

    The sequence is: A, B, C ... Z, AA, AB, AC

    and not: A, B, C ...Z, BA, BB, BC

    (the language is Erlang, mais oui).

提交回复
热议问题