I have this error in a LeetCode question. The post on the discussion section is here. I am doing it in JS but I got an error when executing with some questions
Description:
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
My solution:
/**
* @param {number} columnNumber
* @return {string}
*/
var convertToTitle = function(columnNumber) {
const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var name = "";
while (columnNumber > 0) {
name = name.concat(alphabet[columnNumber%26 - 1]);
columnNumber = columnNumber - columnNumber%26;
}
return(name);
};
When I call the function with colNumber < 26 it works like a charm, but why does the code crash when I execute it with a greater number? I think it is an infinite loop but I am not sure.
You can try to debug on the paper, it will help you a lot.
Imagine you have an input = 27
as first loop it will be
while (columnNumber > 0) {
name = name.concat(alphabet[columnNumber %26 - 1]); #
columnNumber = 27- 27%26;
# columnNumber = 27 - 1 , new columnNumber will be 26
}
seems like it works perfectly but what happens when you run the second loop with the new columnNumber value = 26
while (columnNumber > 0) {
name = name.concat(alphabet[columnNumber %26 - 1]); #
columnNumber = columnNumber - columnNumber %26;
# columnNumber = 26 - 26%26 , 26 mod 26 = 0
# then you will get you inf loop 26 - 0
}
Nice exercise! Quick and dirty code:
function convertToTitle(columnNumber) {
columnNumber -= 1;
let name = "";
let alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
while (columnNumber >= 0) {
if (columnNumber > alphabet.length - 1) {
name = name.concat(alphabet[Math.floor(columnNumber / 25) - 1]);
columnNumber -= Math.floor(columnNumber / 25) * 25;
columnNumber -= 1;
} else {
name = name.concat(alphabet[columnNumber]);
break;
}
}
return name;
}
Edit:
Console Output
Explenation:
1 -> A, but an Array starts at index 0, so columnNumber -= 1
27 -> AB, get the base (A) by dividing with 25 (alphabet.length - 1) and the rest of the division
If columnNumber is <26 (u know, index starts at 0) we can get the char directly.
A bit cleaner way would be the usage of String.charAt(index)
const alphabet = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
alphabet.charAt(0); // returns char at 0 -> A