Google interview question

Define an algorithm that converts a string to an integer without using a built in method like int()

Interview Answers

Anonymous

Jun 3, 2010

in Java: String f = "2456"; int length = f.length(); double result = 0; for (int i = 0; i < length; i++) { char c = f.charAt(i); int x = c - 48; double exp = Math.pow(10,length-1-i); result = result + (exp*x); } int myInt = (int)result;

Anonymous

Aug 19, 2010

Complete python program to convert from string to int. Complexity: o(n), where n is the number of digits of s. ---- s = '2456' n = 0 p10 = 1 for d in reversed(s): n += p10 * (ord(d) - ord('0')) p10 *= 10