LeetCode - Algorithms - 171. Excel Sheet Column Number

这题算Easy,Excel列编号好像可以理解成26进制,少不了查下JDK API Specification,查看JavaScript Bible

Java

1
2
3
4
5
6
7
8
9
10
class Solution {
public int titleToNumber(String s) {
int n = 0;
int len = s.length();
for(int i=s.length()-1;i>=0;i--) {
n += (Character.getNumericValue(s.charAt(i))-9)*Math.pow(26, len-i-1);
}
return n;
}
}

Submission Detail

  • 1000 / 1000 test cases passed.
  • Your runtime beats 5.55 % of java submissions.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {string} s
* @return {number}
*/
var titleToNumber = function(s) {
var n = 0;
var len = s.length;
for(var i=s.length-1;i>=0;i--) {
n+=(s.charCodeAt(i)-64)*Math.pow(26,len-i-1);
}
return n;
};

Submission Detail

  • 1000 / 1000 test cases passed.
  • Your runtime beats 99.02 % of javascript submissions.