TypechoJoeTheme

IT技术分享

统计

[LeetCode 171] Excel Sheet Column Number [Java] [Runtime : 2MS]

2017-09-01
/
0 评论
/
551 阅读
/
正在检测是否收录...
09/01

1. Description

Related to question Excel Sheet Column Title

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

2. Runtime Distribution

3. Submission Details

4. Example

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

5. Code

public int titleToNumber(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }
    int result = 0;
    int times = 1;
    for (int i = s.length() - 1; i >= 0; i--) {
        result += (s.charAt(i) + 1 - 'A') * times;
        times *= 26;
    }
    return result;
}

6.Test

public class LeetCode0171 {
    public int titleToNumber(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int result = 0;
        int times = 1;
        for (int i = s.length() - 1; i >= 0; i--) {
            result += (s.charAt(i) + 1 - 'A') * times;
            times *= 26;
        }
        return result;
    }

    public static void main(String[] args) {
        LeetCode0171 leetcode = new LeetCode0171();
        System.out.println(leetcode.titleToNumber("AC"));
    }
}
Math
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/779/(转载时请注明本文出处及文章链接)