Skip to content

171. Excel Sheet Column Number 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
class Solution {
 public:
  int titleToNumber(string s) {
    return accumulate(begin(s), end(s), 0,
                      [](int a, int b) { return a * 26 + (b - 'A' + 1); });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int titleToNumber(String s) {
    int ans = 0;

    for (final char c : s.toCharArray())
      ans = ans * 26 + c - '@';

    return ans;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def titleToNumber(self, s: str) -> int:
    ans = 0

    for c in s:
      ans = ans * 26 + ord(c) - ord('@')

    return ans