Skip to main content

Given this implementation of atoi in C++

// A simple atoi() function int myAtoi(char *str) {  int res = 0; // Initialize result  // Iterate through all characters of input string and update result  for (int i = 0; str[i] != '\0'; ++i)   res = res*10 + str[i] - '0';  // return result.  return res; } // Driver program to test above function int main() { char str[] = "89789"; int val = myAtoi(str); printf ("%d ", val); return 0; } 

How exactly does the line

res = res*10 + str[i] - '0'; 

Change a string of digits into int values? (I'm fairly rusty with C++ to be honest. )

Given this implementation of atoi in C++

// A simple atoi() function int myAtoi(char *str) { int res = 0; // Initialize result // Iterate through all characters of input string and update result for (int i = 0; str[i] != '\0'; ++i) res = res*10 + str[i] - '0'; // return result. return res; } // Driver program to test above function int main() { char str[] = "89789"; int val = myAtoi(str); printf ("%d ", val); return 0; } 

How exactly does the line

res = res*10 + str[i] - '0'; 

Change a string of digits into int values? (I'm fairly rusty with C++ to be honest. )

Given this implementation of atoi in C++

// A simple atoi() function int myAtoi(char *str) {  int res = 0; // Initialize result  // Iterate through all characters of input string and update result  for (int i = 0; str[i] != '\0'; ++i)   res = res*10 + str[i] - '0';  // return result.  return res; } // Driver program to test above function int main() { char str[] = "89789"; int val = myAtoi(str); printf ("%d ", val); return 0; } 

How exactly does the line

res = res*10 + str[i] - '0'; 

Change a string of digits into int values? (I'm fairly rusty with C++ to be honest. )

Source Link
user3708902
  • 161
  • 1
  • 2
  • 13

atoi implementation in C++

Given this implementation of atoi in C++

// A simple atoi() function int myAtoi(char *str) { int res = 0; // Initialize result // Iterate through all characters of input string and update result for (int i = 0; str[i] != '\0'; ++i) res = res*10 + str[i] - '0'; // return result. return res; } // Driver program to test above function int main() { char str[] = "89789"; int val = myAtoi(str); printf ("%d ", val); return 0; } 

How exactly does the line

res = res*10 + str[i] - '0'; 

Change a string of digits into int values? (I'm fairly rusty with C++ to be honest. )