LeetCode之Excel Sheet Column Number

133 阅读1分钟

1、题目

 

Related to question Excel Sheet Column Title

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 

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

 

 

 

 

 

2、分析

 

A -> 1*26^0

AA -> 1*26^1 + 1*26^0

AAA -> 1*26^2 + 1*26^1 + 1*26^0

 

 

 

 

 

 

3、代码实现

 

public class Solution {
    public int titleToNumber(String value) {
       if (value == null || value.length() == 0) 
			return 0;
		int length = value.length();
		//A 65
		char[] chars = value.toCharArray();
		int result = 0;
		int pow = 0;
		//please here is i >= 0 not is i > 0
		for (int i = length - 1; i >= 0; i--) {
			int tmp = chars[i] - 'A' + 1;
			int temp1 = (int)Math.pow(26, pow);
			pow++;
			result += tmp * temp1;
		}
		return result; 
    }
}

 

 

 

 

 

 

 

4、总结

注意每次写

 

for(int i = length - 1; i > 0 --i)

 

 

 

的时候要注意不是这样写的,需要写成这样

 

for(int i = length - 1; i >= 0 --i)


不要忘记有=号,切记,以后不要换这样的错误。

 

还有求^的函数要知道,不要忘记

 

Math.pow(26, pow)