关闭

[leetcode] 171. Excel Sheet Column Number

标签: leetcodeeasy
72人阅读 评论(0) 收藏 举报
分类:

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

For example:

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28  

Solution:

Idea: similar to binary numbers, base = 26

<span style="font-size:14px;">class Solution {
public:
    int titleToNumber(string s) {
        int ret = 0;
        for(int i = 0; i < s.size(); i++){
            int digit = s[i] - 'A' + 1;
	    # ret += pow(26, s.size()-i-1) * digit;
            ret += power(26, s.size()-i-1) * digit;
        }
        return ret;
    }
    
    int power(int base, int index){
        int ret = 1;
        for (int i = 0; i < index; i++)
            ret *= base;
            
        return ret;
    }
};</span>




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11793次
    • 积分:642
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:150篇
    • 译文:0篇
    • 评论:0条
    文章分类