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
Solution:
可以看出规律是 number = number * 26 + s.charAt(i) - 'A' + 1
Run time complexity is O(n), constant space.
public class Solution { public int titleToNumber(String s) { if(s == null || s.length() == 0) { throw new IllegalArgumentException("Input string is invalid!"); } int i = 0; int number = 0; while(i < s.length()) { number = number * 26 + s.charAt(i) - 65 + 1; // s.charAt(i)-'A'+1 i++; } return number; } }
No comments:
Post a Comment