0

I was asked in a Java interview to write a program that would convert a string for example "123" into number 123 without using any of java's conversion functions/utility classes.

I am still confused if that would be possible. Any ideas ? Thanks

1
  • what counts as a utility class? Could you have a map of strings to numbers, iterate over the string, look up the number by the string, and construct the number? Commented Apr 16, 2012 at 19:52

2 Answers 2

1

Break the string into individual characters, map each to its numeric value, and combine by multiplying each by its place value.

Sign up to request clarification or add additional context in comments.

Comments

0

I should have made my comment an answer so I can get the answer credit :)

"what counts as a utility class? Could you have a map of strings to numbers, iterate over the string, look up the number by the string, and construct the number?"

in pseudocode:

Map<String, Integer> = {
"0":0,
"1":1,
"2":2,
... etc }

int number = 0;

for(i=string.length-1; i>=0; i--){
String substr = string.substring(i, i+1);
int digit = map.get(substr);
number += 10^(string.length-i)*digit;
}

return number

6 Comments

Colleen as per your supplied code, I wrote following: Map<String, Integer> map = new HashMap<String, Integer>(); map.put("0", 0); map.put("1", 1); map.put("2", 2); map.put("3", 3); map.put("4", 4); map.put("5", 5); map.put("6", 6); map.put("7", 7); map.put("8", 8); map.put("9", 9); int number = 0; String myNumber = "456"; for(int i=0; i < myNumber.length() - 1; i++) { String substr = myNumber.substring(i, i+1); int digit = map.get(substr); number += 10 ^ i * digit; } System.out.println(number); Output: 25 This seems to be incorrect. Can you plz tell where I am wrong. Thanks
Also "map" is a complex Java object and I guess it might involve some automatic conversion when we use map.get() function. I wonder if the interviewer was concerned getting it some simpler way.
You're going to need to convert from Integer to int (I didn't because it was pseudocode). So it should work if you do int digit = (int) map.get(substr)
Also, the calculation for digit was off and I forgot that substring is inclusive, exclusive. Sorry about that! I edited the code to reflect these changes.
I'm not sure how to do it any simpler, though. Except maybe like 2 arrays that essentially act as a map?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.