Monthly Archives: December 2010

Languages and their Operators

Did you know that in JavaScript, if you do this:

'5' + 3

You will get 53, because it coerced the 3 into a string when it needed to perform a concatenation ‘+’ operation against the string ’5′.

But if you do this:

'5' - 3

You will get 2, because it coerced the string ’5′ into a number to perform subtraction against another number.

That’s what happens when you have a weakly typed language; It attempts to do the right thing based upon the operator and operands, and you’ve got to be careful to understand whats going on.

Another oddity… In Java:

Integer foo = 1000;
Integer bar = 1000;

foo = bar; // true
foo == bar; // false

The above happens because the first two operations are numeric equality checks, while the last is a reference equality check. ‘foo’ and ‘bar’ do represent numeric values, but are not the same reference.

Number System Interview Questions

The following 2 interview questions can help gauge whether a candidate understands number systems.

//converts string '123' to numeric 123.
private static int Atoi(string number)
{
    int result = 0;
    int multiplier = 1;

    for (int idx = number.Length - 1; idx >= 0; idx--)
    {
        char digitChar = number[idx];
        int digitValue = digitChar - '0';
        result += (digitValue * multiplier);
        multiplier *= 10;
    }

    return result;
}

//determines the number of bits turned on in a number
private static int BitCount(int number)
{
    int bits = 0;
    while (number > 0)
    {
        bits += (number % 2);
        number /= 2;
    }

    return bits;
}