Interviewer: Square each digit of number without using any string function
Recently I gave an interview for the role Sr. Frontend Developer. The Interviewer asked me this question:
Q: Square each digit of a given number — 9191 => 811811
Right after seeing the question I started implementing it, using inbuilt JavaScript function this was pretty much easy.
Here is the solution which I proposed:
After seeing this code, he wasn’t satisfied 😞, He asked me to do it without using any string functions.
I thought of a little but, and right after few seconds It was clear that if we have to do this without using string
method then we have to do two extra things:
- Reverse the number — because if we run a loop over number we will get result in reverse order.
- Find the number of zero needs to be added to a number: We don’t know how big the square would be, so we need to dynamically find the number.
All these programs I wrote while I was in my college, so I simply have to recall those days and this was the piece of code which I came up with: