Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Strings

Excel Column Number

Easy · Strings · Asked at Microsoft, Amazon, Zoho

Spreadsheet columns are named A = 1, B = 2, …, Z = 26, AA = 27, AB = 28, … Print the number of the given column title.

Input

A single line with the title (capital letters only).

Output

The column number.

Constraints

Example 1

Input

AB

Output

28

Example 2

Input

ZY

Output

701

Hints

  1. Read the title like a base-26 number, left to right.
  2. Each letter is worth its position in the alphabet: A = 1 … Z = 26.

Approach

Start with 0 and, for every letter, multiply by 26 and add (letter − 'A' + 1). "AB" = 1 × 26 + 2 = 28. The answer fits in a 32-bit signed integer, but a 64-bit variable avoids any doubt during the last multiplication.

Complexity: O(length) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    long long n = 0;
    for (char c : s) n = n * 26 + (c - 'A' + 1);
    cout << n << "\n";
    return 0;
}

Python solution

s = input().strip()
n = 0
for c in s:
    n = n * 26 + (ord(c) - ord("A") + 1)
print(n)

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String s = new Scanner(System.in).next();
        long n = 0;
        for (char c : s.toCharArray()) n = n * 26 + (c - 'A' + 1);
        System.out.println(n);
    }
}

Solve Excel Column Number online · All practice problems