Excel Sheet Column Problem

Introduction

In this algorithm challenge on LeetCode, I decided to tackle the Excell Column Sheet Problem. This problem required me to take an alphabet string that represented integer values, for example, the letter “A” would represent 1, “B” would represent 2, and so forth. However, there is a particular trick to this problem. If the string happened to be “AA” it would result in 27. The base number, which is 26 is added to the string value. For an understanding, let’s break it down below.

`Input: columnTitle = "A"Output: 1Input: columnTitle = "AB"Output: 28because 1 * 26 + 2 = 28. Remember 26 is our base number when having more than one characters. `

The Breakdown

My initial thought process was to store the letters into objects with key-value pairs. This would allow me to connect the letter and number to the string in my arguments. Here is a better look below.

`function titleToNumber(s){let letters = {A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7, H: 8, I: 9, J: 10, K: 11, L: 12, M: 13, N: 14, O: 15, P: 16, Q: 17, R: 18, S: 19, T: 20, U: 21, V: 22, W: 23, X: 24, Y: 25, Z: 26}}`

I created a variable called num and set it to zero. This would later be used to increment the number and return it.

`function titleToNumber(s){let letters = {A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7, H: 8, I: 9, J: 10, K: 11, L: 12, M: 13, N: 14, O: 15, P: 16, Q: 17, R: 18, S: 19, T: 20, U: 21, V: 22, W: 23, X: 24, Y: 25, Z: 26}let num = 0}`

Furthermore, I looped through the entire string. Within the loop, I decided to multiply the num to the base and add it to the object of the current index. Here is a better look below.

`function titleToNumber(s){let letters = {A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7, H: 8, I: 9, J: 10, K: 11, L: 12, M: 13, N: 14, O: 15, P: 16, Q: 17, R: 18, S: 19, T: 20, U: 21, V: 22, W: 23, X: 24, Y: 25, Z: 26}let num = 0for(let i = 0; i < s.length; i++){  num = num * 26 + letters[s[i]]}}`

Once those steps were completed I simply return the num. Here is a full look below.

`function titleToNumber(s){let letters = {A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7, H: 8, I: 9, J: 10, K: 11, L: 12, M: 13, N: 14, O: 15, P: 16, Q: 17, R: 18, S: 19, T: 20, U: 21, V: 22, W: 23, X: 24, Y: 25, Z: 26}let num = 0for(let i = 0; i < s.length; i++){  num = num * 26 + letters[s[i]]}return num}console.log(titleToNumber("A"))`

Thanks for reading. if there are any questions just post in the comment?

--

--

--

More from Woodelin florveus

Love podcasts or audiobooks? Learn on the go with our new app.