码迷,mamicode.com
首页 > 其他好文 > 详细

Excel Sheet Column Title

时间:2015-03-14 21:33:49      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

Excel Sheet Column Title

问题:

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

思路:

  进制访问问题

我的代码:

技术分享
public class Solution {
    public String convertToTitle(int n) {
        StringBuffer sb = new StringBuffer();
        if(n <= 0)  return sb.toString();
        
        while(n != 0)
        {
            sb.append(getChar((n - 1)%26));
            n = (n - 1)/26;
        }
        return sb.reverse().toString();
    }
    public char getChar(int num)
    {
        return (char)(‘A‘ + num);
    }
}
View Code

他人代码:

技术分享
public class Solution {
    public String convertToTitle(int n) {
        StringBuilder result = new StringBuilder();
        while(n>0)
        {
            result.append((char) ((n-1)%26 + (int)‘A‘));
            n = (n-1)/26;
        }
        return result.reverse().toString();
    }
}
View Code

学习之处:

  • 在Java里 char是两个字节,int是四个字节,所以char转int要用上强制转换,经常忘记这一点,已经有好几次warning了。
  • 平常是用s += part 未曾想 s = part + s 这样便可以轻松的实现reverse了,学习了,具体实现在他人的代码里面有。

Excel Sheet Column Title

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4338156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!