leetcode 168. Excel Sheet Column Title

来源:互联网 发布:java开发环境包括 编辑:程序博客网 时间:2024/06/05 04:26

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

For example:

1 -> A2 -> B3 -> C...26 -> Z27 -> AA28 -> AB 

这道题考察的是26进制数据的转化。

代码如下:

public class Solution {    /*     * 就是一个10进制数据转换为26进制的数据,不过要注意这里是从1开始,     * 不是从0开始的     * */    public String convertToTitle(int n)     {        String res = "";        while( n>0 )        {            res = (char)((int)('A')+(n-1)%26) + res;            n = (n-1)/26;        }        return res;    }}

下面是C++的做法,就是一个26进制数据的jisuan

代码如下:

#include <iostream>#include <string>using namespace std;class Solution {public:    string convertToTitle(int n)     {        string res = "";        while (n>0)        {            res = (char)((int)('A') + (n - 1) % 26) + res;            n = (n - 1) / 26;        }        return res;    }};
原创粉丝点击