题意:

image.png

解题思路:

  1. 思路:
  2. (0~25ASCII则在每位+'A'),PHP则加上65,因为chr(65) == A
  3. 0, 1, 2, 3.......25
  4. + 'A'
  5. A, B, C, D.......Z
  6. -------------------------
  7. 问题:1 % 26 => 1 ??跟题目的0不一致,1映射到B,但题目实际要求映射到了A
  8. 解决办法:对整数 -1(减一),即 0 % 26 =》00映射到了A

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer $n
  4. * @return String
  5. */
  6. function convertToTitle($n) {
  7. if ($n <= 0) return "";
  8. $s = "";
  9. while ($n > 0) {
  10. $n--;
  11. $s = chr(fmod($n, 26) + 65). $s;
  12. $n = floor($n / 26);
  13. }
  14. return $s;
  15. }
  16. }

go代码实现:

  1. func convertToTitle(n int) string {
  2. s := ""
  3. for n != 0 {
  4. n--
  5. s = string(n % 26 + 'A') + s
  6. n /= 26
  7. }
  8. return s
  9. }