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

前端 未结 28 1410
[愿得一人]
[愿得一人] 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条回答
  •  猫巷女王i
    2020-11-29 22:38

    Wikipedia has good explanations and algos

    http://en.wikipedia.org/wiki/Hexavigesimal

    public static String toBase26(int value){
        // Note: This is a slightly modified version of the Alphabet-only conversion algorithm
    
        value = Math.abs(value);
        String converted = "";
    
        boolean iteration = false;
    
        // Repeatedly divide the number by 26 and convert the
        // remainder into the appropriate letter.
        do {
            int remainder = value % 26;
    
            // Compensate for the last letter of the series being corrected on 2 or more iterations.
            if (iteration && value < 25) {
                remainder--;
            }
    
            converted = (char)(remainder + 'A') + converted;
            value = (value - remainder) / 26;
    
            iteration = true;
        } while (value > 0);
    
        return converted;    
    }
    

提交回复
热议问题