My code:
public class Solution {
public int titleToNumber(String s) {
if (s == null || s.length() == 0)
return 0;
int number = 0;
for (int i = 0; i < s.length(); i++)
number = number * 26 + s.charAt(i) - 64;
return number;
}
}
My test result:
这道题目太简单了,感觉有点侮辱智商。
**
总结: Math
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int titleToNumber(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int base = 1;
int ret = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char curr = s.charAt(i);
int diff = (int) (curr - 'A') + 1;
ret += diff * base;
base *= 26;
}
return ret;
}
}
以前的解法竟然看不懂。。。还大言不惭,侮辱智商。。。
是我变笨了吗?
Fuck
我的思想是找规律:
A-Z: 1-26
AA-AZ: 27-52
BA-BZ: 53-78
...
AAA: 703
AAA = 1 * 26 ^ 2 + 1 * 26 ^ 1 + 1 * 26 ^ 0
从这个公式,也可以看出
Excel Sheet Column Title
那么做的原因了。
int offset = (n - 1) % 26;
while (n > 0) {
ret = ('A' + offset) + ret;
n = (n - 1) / 26; // 去掉 k * (26 ^ x), here 1<=k<=26, so n - 1
col = (n - 1) % 26; // keep finding the offset of next level
}
感觉差不多就这个思路。
Anyway, Good luck, Richardo! -- 09/05/2016
这些天有了新的思路。其实就是一个26进制转换。
AB
'B' * 26 ^ 0 + 'A' * 26 ^ 1
= 2 * 1 + 1 * 26 = 28
然后可以很快的写出代码:
My code:
public class Solution {
public int titleToNumber(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int base = 1;
int ret = 0;
for (int i = s.length() - 1; i >= 0; i--) {
int offset = (int) (s.charAt(i) - 'A') + 1;
ret += base * offset;
base *= 26;
}
return ret;
}
}
终于变成了 easy
Anyway, Good luck, Richardo! -- 09/19/2016