Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
String to Integer (atoi) in C++
Suppose we have to design a module, that first discards as many whitespace characters as necessary until the first non-whitespace character is reached. After that, starting from this character, it takes an optional initial plus sign or minus sign followed by as many numerical digits, and interprets them as a numerical value.
When the first sequence of non-whitespace characters in str is not a valid integral number, or when no such sequence exists because either str is empty or it contains only whitespaces, no conversion will be performed.
So if the input is like “-45”, the output will be -45.
To solve this, we will follow these steps −
- sign := 1, base := 0, i := 0, n := size of the string s
- while i < n and s[i] is whitespace, then increase i by 1
- if the first character is – then sign := -1, otherwise sign := 1
- while s[i] in range ‘0’ to ‘9’
- read each character and convert it to an integer, then adjust the base calculation by increasing base for each character.
- return the number * sign
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int myAtoi(string str) {
int sign = 1;
int base = 0;
int i = 0;
int n = str.size();
while(i < n && str[i] == ' '){
i++;
}
if(str[i] == '-' || str[i] == '+') sign = 1 - 2*(str[i++] =='-');
while(str[i] >= '0' && str[i] <='9'){
if(base > INT_MAX/10 || base == INT_MAX/10 && str[i]- '0' > INT_MAX %10){
if(sign == 1)return INT_MAX;
return INT_MIN;
}
base = (base * 10) + (str[i++] - '0');
}
return base * sign;
}
};
main(){
Solution ob;
cout << ob.myAtoi("-45")<<endl;
cout << ob.myAtoi(" 56")<<endl;
cout << ob.myAtoi("100")<<endl;
}
Input
"-45" " 56" "100"
Output
-45 56 100
Advertisements