LeetCode 171. Excel Sheet Column Number (Excel 表格列数字)
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
题目标签:Math
这一题和 #168 是逆向思维。
从string s 的最右边遍历,每次拿一个 char, 减去 ‘A’, 记得要加1才得到正确的值。
剩下的就和10进制是一样的,还要乘以 1, (26^1, 26^2, ...)
Java Solution:
Runtime beats 52.26%
完成日期:06/14/2017
关键词:26进制
关键点:A 对应 1,所以要 + 1
1 class Solution 2 { 3 public int titleToNumber(String s) 4 { 5 int res = 0; 6 int mul = 1; 7 8 // iterate s from right to left 9 for(int i = s.length() - 1; i >= 0; i--) 10 { 11 res = (s.charAt(i) - 'A' + 1) * mul + res; // need to + 1 cause A - 1 12 mul *= 26; // need to multiply 26 for next round 13 } 14 15 return res; 16 } 17 }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/