Saturday, July 2, 2016

Google interview question: write an execl col label to integer converter

// http://www.impactinterview.com/2009/10/140-google-interview-questions/#software_engineer
// Write a function (with helper functions if needed) called to Excel that takes an excel column value
// (A,B,C,D…AA,AB,AC,… AAA..) and returns a corresponding integer value (A=1,B=2,… AA=26..).

#include <iostream>
#include <stdexcept>

// the function "toExecl" will convert *from* excel format to integers... ignoring that confusion...
int fromExcel(std::string val)
{
    // there is an oddity here
    // 0A -> A but A0 -> doesnt exist! note the +1 in the conversion line as a result

    int out = 0;
    for (std::string::iterator vit = val.begin();
         vit != val.end();
         ++vit)
    {
        if (*vit < 'A' or *vit > 'Z')
            throw std::runtime_error("doesnt look like an execl col");
        out = (out*26) + (*vit - 'A' + 1);
    }

    return out;
}

int test(std::string in, int exp)
{
    int out = fromExcel(in);

    std::cout << (out == exp ? "passed" : "FAILED")
              << " in:" << in
              << " out:" << out
              << " exp:" << exp
              << "\n";
}

int main()
{
    try
    {
        test("012", 0);
        std::cout << "FAILED: did not detect bad inputs\n";
    }
    catch (std::exception& e)
    {
        std::cout << "pass: throw check worked\n";
    }

    test(  "A",                     1);
    test(  "Z",                    26);
    test( "AA",             1*26 +  1);
    test( "AZ",             1*26 + 26);
    test( "BA",             2*26 +  1);
    test( "ZZ",            26*26 + 26);
    test("AAA", 1*26*26 +   1*26 +  1);
    test("AZZ", 1*26*26 +  26*26 + 26);
    test("ZAA",26*26*26 +   1*26 +  1);
    test("ZZZ",26*26*26 +  26*26 + 26);
}

Output

pass: throw check worked
passed in:A out:1 exp:1
passed in:Z out:26 exp:26
passed in:AA out:27 exp:27
passed in:AZ out:52 exp:52
passed in:BA out:53 exp:53
passed in:ZZ out:702 exp:702
passed in:AAA out:703 exp:703
passed in:AZZ out:1378 exp:1378
passed in:ZAA out:17603 exp:17603
passed in:ZZZ out:18278 exp:18278

No comments:

Post a Comment