## Interview Question

## Interview Answer

4 Answers

why do you need Math.pow()?

will this work?

fun() // input 5467

// take first character and transform into integer

//multiply by 10 * index of character which is zero

that is 5 + 0 = 5

then take the next character and transform into integer

now multiply 5 * 10 * index of character which is one

50 +4 = 54

repeat

540+ 6 = 546

5460 + 7 = 5467

running time is O(k) k = no of digits

or O(n) n being the number

The way I did it was (for your example of 5467) essentially 5000 + 400 + 60 + 7. It's the first solution that came to mind and since that hour long portion of the interview seemed to be winding down, I just went with it. Not a pretty solution, but it does get the right answer.

For your solution, I understand what you're doing but I think your description of it is a bit off, or at least confusing. The you don't multiply by the index of the character at any time. What you're doing is just multiplying the sum to that point by 10 before adding the next character... i.e. in pseudo code,

sum = 0;

n = (length of the string of characters);

for(i==0; i < n; i++) {

sum *= 10;

sum+= (converted integer value of the character at index i);

}

So the first time through the loop when the index is zero, the initial sum multiplied by 10 is still zero, so you add 5 and get the running sum to be 5. Iteration 2, 5*10 = 50, add the next integer and you get 54, and so on. And that is a far more elegant solution, definitely. Thanks for pointing it out!

If Java is allowed than why to do all these things. Why not directly use wrapper calss Integer and convert a string to integer.

String s="12345";

int i = Integer.parseInt(s);

Simple !

## Add Answers or Comments

To comment on this question, Sign In with Facebook or Sign Up

You can do math on individual characters, so subtract a constant from '5' and you can transform that character into an actual integer, 5. Then you need the String class and the Math.Pow() function. Don't forget to import the library that contains Math.Pow() !

Feb 8, 2012