天天看點

LeetCode之Excel Sheet Column Number

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)

繼續閱讀