C# O(N) Simple, Readable


  • 1
    B
    public class Solution 
    {
        public int TitleToNumber(string s) 
        {
            var num = 0;
            var pow = s.Length - 1;
            
            foreach(var letter in s)
            {
                // convert 'A'-'Z' to 1-26
                int val = (int)letter - '@'; // @ == A - 1
    
                // base26 digit to decimal number
                num += val * (int)Math.Pow(26, pow--);
            }
            return num;
        }
    }
    

    This solution relies on the principle that the letter encoding (AA, BBCE ect.) can be viewed as a base 26 number. This number is converted into decimal by the formula decimal = digit * 26 ^ (place) where place is the number of digits from the right (IE 1, 26, 26^2, 26^3 ect), the rightmost digit being 0, although technically this algorithm starts from the left so that foreach() was usable :P


Log in to reply
 

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