Implement the atoi() function, which converts a string to a 32-bit signed integer.
Example:
Input: str="4193 with words" Output: 4193
Approach
Java
public class StringToInteger {public static void main(String[] args) {String str = "4193 with words";System.out.println(myAtoi(str));}// method to convert string to intpublic static int myAtoi(String s) {String v = null;boolean sign = false, chars = false;for (int i = 0; i < s.length(); i++) {if (!sign && v == null && (!Character.isDigit(s.charAt(i)))&& s.charAt(i) != '-' && s.charAt(i) != '+'&& s.charAt(i) != ' ') {return 0;} else if (v == null && (s.charAt(i) == '-' || s.charAt(i) == '+')) {if (sign || chars)return 0;v = "" + s.charAt(i);sign = true;} else if (Character.isDigit(s.charAt(i))) {if (v != null)v = v + "" + s.charAt(i);elsev = "" + s.charAt(i);chars = true;if (Long.parseLong(v) >= Integer.MAX_VALUE)return Integer.MAX_VALUE;else if (Long.parseLong(v) <= Integer.MIN_VALUE)return Integer.MIN_VALUE;} else if ((sign || chars) && (!Character.isDigit(s.charAt(i))))break;}if (v == null || !chars)return 0;elsereturn Integer.parseInt(v);}}
C++
#include <bits/stdc++.h>using namespace std;int myAtoi(string str){int n=str.size();int i=0;//itearte till their is spaceswhile(i<n&&str[i]==' ')i++;if(str[i]=='+'){i++;if(str[i]=='-'||str[i]=='+')return 0;}if(str[i]!='-'&&(!isdigit(str[i])))return 0;string res="";for(int j=i;j<str.size();j++)res+=str[j];stringstream str1(res);int x = 0;str1>> x;return x;}int main(){string str="4193 with words";cout<<myAtoi(str);return 0;}
No comments:
Post a Comment