As an example, a question I got last night was along the lines of:
Write a function that takes two integers, and returns a string representing their sum as expressed in binary.
So, the meat of this problem is converting an integer from base 10 to binary.
In Java, you might do this:
Rather than just Googling it, I figured I may as well solve the problem manually first, for the exercise of it.
My general approach to the problem was to:
- deconstruct the integer into an array of decreasing powers of 2
- iterate though the array, returning a
1depending on whether the next smallest power of 2 is next in the array
According to MDN,
Object.prototype.toString() with the useful distinction that you can pass in a single integer argument. This argument is an optional radix, numbers
So in the example above, we’re passing in
2 to get a string representation of the binary for the base 10 number
It’s likely that you’ve written something like
myNum.toString() before without incident, possibly without being aware that there is a
Number object override of
.toString(). This is because when you don’t pass in the optional radix,
Number.prototype.toString() assumes you want a base 10 string representation, and
"100", just as you would expect.
It’s also fun to think about how you would approach the problem without the aide of such a built-in method. It will make you appreciate having them all the more.