[leetcode]171.Excel Sheet Column Number

题目

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 
...

Example 1:

Input: "A"
Output: 1
Example 2:

Input: "AB"
Output: 28
Example 3:

Input: "ZY"
Output: 701

解法

思路

此题比较简单,提供两种写法,思路是一样的.

代码一

class Solution {
    public int titleToNumber(String s) {
        int n = s.length();
        int res = 0;
        for(int i = 0; i < n; i++) {
            res += (s.charAt(i)-64) * Math.pow(26, n-1-i);
        }
        return res;
    }
}

代码二

public class Solution {
    public int titleToNumber(String s) {
    
        int result  = 0;
        for (int i = 0; i < s.length(); i++){
            result *= 26;
            result += ((s.charAt(i) - 'A') + 1);    
        }
    
        return result;
    }
}

猜你喜欢

转载自www.cnblogs.com/shinjia/p/9764268.html