Microsoft interview question

Write a function to turn a string into an integer and test it

Interview Answers

Anonymous

Nov 24, 2010

public int AtoI(string str) { bool isNeg = false; int index = 0; if (str[0] == '-') { isNeg = true; index++; } int result = 0; // "123" 123 // 1 * 10 + 2 12 * 10 + 3 int multiple = 1; int number = 0; for (int i = index; i < str.Length; i++) { number = str[i] - '0'; result = result * multiple + number; multiple = 10; } if (isNeg) { result = result * -1; } return result; }

1

Anonymous

Oct 8, 2010

CString csNum; int nNum = 2; csNum.format("%d", nNum);

Anonymous

Oct 8, 2010

oops wrong one CString csNum = "1"; int nNum = atoi(csNum);