My simple JAVA solution 2ms


  • 0
    N

    I think it was just the matter of finding a pattern and then putting it into code. Here is an example, let's say ABCD. There are 26 letters, so in order to reach AA it will be 27 or 26 ^1+1 (1 for 'A'). Similarly, to reach AAA we have to use 26 letter 26 times ( because you have to go through AA, AB,AC,....BA,BB,BC....ZA,ZB,ZC ) so 26^2+1 and so on for AAAA it will be 26^3+1. Now, coming back to the example ABCD will be 26^3*1+26^2*2(for another cycle since it's B)+26^1*3+4 (for D) equals 19010. I hope my explanation make sense.

    public class Solution {
        public int titleToNumber(String s) {
            int col = 0,pow=0;
            for(int i=s.length()-1;i>=0;i--){
               col+= Math.pow(26,pow)*((s.charAt(i)-64));
               pow++;
            }
            return col;
            
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.