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

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

    Get a column name from an int in Java(read more here):

    public String getColName (int colNum) {
    
       String res = "";
    
       int quot = colNum;
       int rem;        
        /*1. Subtract one from number.
        *2. Save the mod 26 value.
       *3. Divide the number by 26, save result.
       *4. Convert the remainder to a letter.
       *5. Repeat until the number is zero.
       *6. Return that bitch...
       */
        while(quot > 0)
        {
            quot = quot - 1;
            rem = quot % 26;
            quot = quot / 26;
    
            //cast to a char and add to the beginning of the string
            //add 97 to convert to the correct ascii number
            res = (char)(rem+97) + res;            
        }   
        return res;
    }
    

提交回复
热议问题