171. Excel Sheet Column Number
Question:
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:
Input: "A"
Output: 1
Input: "AB"
Output: 28
Input: "ZY"
Output: 701
Source code:
Version 1
Idea:
The type of input is string, so we need to split it into characters, and convert character to demical by using ASCII talbe.
Each digit will times 26 to the power of (len - i - 1)
.
Why is (len - i - 1)
means? If input is "AB" (len=2), we get "A" character first, and "A" is tens digit, so use the fourmula (2 - 0 - 1) the power is 1,then you can get 26. pow(26, 1) * (65 - 64)
Furthermore, the next character is "B", the power is 0, so you get 2. pow(26, 0) * (66-64)
Hence, the results is 28 (26+2).
Time complexity: O(n)
Space complexity: O(1)
1 | class Solution { |
Version 2
Idea:
The runtime of Version 2 will get more faster than Version 1. Because it's not use pow() function.
A logic likes : (previous_sum * 26 + current_sum), so the sum times 26 for each loop (= each digit)
Time complexity: O(n)
Space complexity: O(1)
1 | class Solution { |