Letter increment

by Adam Granger

JavaScript

function count_to_string(n) {
    var div = n;
    var remainder, output = "";
    while (div != 0) {
        remainder = div % 26;
        if (remainder != 0) {
            output = String.fromCharCode(65 + remainder - 1) + output;
        }
        div = Math.floor(div / 26);
    }
    return output;
}

function test(input, expected) {
    var output = count_to_string(input);
    if (output !== expected) {
        throw new Error("Expected " + expected + " got " + output);
    } else {
        console.log(input + " => " + output);
    }
}

test(1, "A");
test(2, "B");
test(3, "C");
test(25, "Y");
test(26, "Z");
test(27, "AA");
test(28, "AB");
test(52, "AZ");
test(53, "BA");
test(54, "BB");
test(55, "BC");
test(78, "BZ");
test(79, "CA");
test(80, "CB");
test(702, "ZZ");