Only trick is the 'Z'. Because when the number % 26 == 0, means there is a 'Z'. But when you n/=26, there is an extra 1 added to the n. EX:

27 % 26 = 1, 27 / 26 = 1  == > AA

26 % 26 = 0, 26 / 26 = 1  Here this extra one need to be removed. You can imagine that 'Z' becomes next around of the loop.

 

 1 class Solution {
 2 public:
 3     string convertToTitle(int n) {
 4         string result;
 5         while (n > 0) {
 6             int tmp = n%26;
 7             n /= 26;
 8             if (tmp == 0) {
 9                 result = 'Z' + result;
10                 n--;
11             } else {
12                 result = char(tmp + 'A' - 1) +result;
13             }
14         }
15         return result;
16     }
17 };

 

posted on 2015-03-19 09:11  keepshuatishuati  阅读(127)  评论(0编辑  收藏  举报