https://leetcode.com/problems/excel-sheet-column-number/\#/description
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
思路:
formula:
假设 abcd 为column number,a,b,c,d都是变量,范围是 A - Z (1 - 26),对应的number n 为:
n = a * 26^3 + b * 26^2 + c * 26^1 + d * 26^0
Q1: 如何求出对应的d呢?
假设 d1 = d - 1 , d1的范围[0, 25] 依次对应相应的A - Z
==> n = a * 26^3 + b * 26^2 + c * 26^1 + (d1 + 1) * 26^0
==> n - 1= a * 26^3 + b * 26^2 + c * 26^1 + d1
==> d1 = (n - 1) % 26
(n - 1) / 26 = a * 26^2 + b * 26^1 + c (jump to Q1 again)
Code相应为:
public class Solution {
public String convertToTitle(int n) {
StringBuilder sb = new StringBuilder();
while(n > 0) {
char c = (char)('A' + (n - 1) % 26);
n = (n - 1) / 26;
sb.insert(0, c);
}
return sb.toString();
}
}