[Leetcode][171. Excel Sheet Column Number] 2 Solutions: Base Conversion From Left to Right and From Right to Left

By Long Luo

This article is the solution of Problem 171. Excel Sheet Column Number.

Base conversion

Basiclly, It’s base conversion.

We are familiar base 1010. How do we calculate a number?

From high to low, starting with ansans as 00, update ansans with the current digit value each time, the update rule is ans=ans×10+valans = ans \times 10 + val.

If there is a decimal number, encoded as ABC\textit{ABC} not the arabic number, what’s it?

1
2
3
4
ans = 0
ans = ans * 10 + 1 => A
ans = ans * 10 + 2 => B
ans = ans * 10 + 3 => C

The answer is: 123.

Right to Left

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int titleToNumber(String columnTitle) {
int n = columnTitle.length();
int ans = 0;
int base = 1;
for (int i = n - 1; i >= 0; i--) {
int temp = 0;
if (columnTitle.charAt(i) == 'Z') {
temp = 26;
} else {
temp = columnTitle.charAt(i) - 'A' + 1;
}
ans = ans + base * temp;
base *= 26;
}

return ans;
}

Left to Right

1
2
3
4
5
6
7
8
9
10
public int titleToNumber_base26(String columnTitle) {
int len = columnTitle.length();
int ans = 0;
for (int i = 0; i < len; i++) {
int num = columnTitle.charAt(i) - 'A' + 1;
ans = ans * 26 + num;
}

return ans;
}

Analysis

  • Time Complexity: O(N)O(N), NN is the length of the string columnTitle.
  • Space Complexity: O(1)O(1)

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗