Convert integer into its character equivalent, where 0 => a, 1 => b, etc

前端 未结 12 861
无人共我
无人共我 2020-11-28 02:52

I want to convert an integer into its character equivalent based on the alphabet. For example:

0 => a
1 => b
2 => c
3 => d

etc.

12条回答
  •  时光说笑
    2020-11-28 03:33

    The only problemo with @mikemaccana's great solution is that it uses the binary >> operator which is costly, performance-wise. I suggest this modification to his great work as a slight improvement that your colleagues can perhaps read more easily.

    const getColumnName = (i) => {
         const previousLetters = (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '');
         const lastLetter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26]; 
         return previousLetters + lastLetter;
    }
    

    Or as a one-liner

    const getColumnName = i => (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '') + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];
    

    Example:

    getColumnName(0); // "A"
    getColumnName(1); // "B"
    getColumnName(25); // "Z"
    getColumnName(26); // "AA"
    getColumnName(27); // "AB"
    getColumnName(80085) // "DNLF"
    

提交回复
热议问题