Given a string str of size N, containing ‘ ‘, ‘.’, ‘-‘, ‘+’, and [‘0’-‘9’], the task is to find the valid integer from this string.
An integer is known as valid if follows the following rules:
- If str has leading whitespaces, ignore them.
- The first valid character should be ‘-‘, ‘+’, or [‘0’-‘9’]
- If no sign is given, treat the integer as positive
- If there are other invalid characters before the integer, print 0.
- If there are invalid characters after the integer, print the integer
- If the number is a decimal number, convert it into an integer
- Ignore any leading 0s
- Make the integer is in range [-2^31, 2^31-1], and if not, print the corresponding limit.
- Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
Examples:
Input: s = “28”
Output: 28
Explanation: As per the given rules 42 is a valid integer.
Input: s = ” -2″
Output: -2
Explanation: Leading white spaces are ignored
Input: s = ” -one6″
Output: 0
Explanation: Invalid character before the integer
Approach: Create a variable to hold the final integer and make it long as the limit might get broken.
Traverse the string character by character, and keep flags for the first digit found and negative:
- If no digit is found yet, and:
- character is space, ignore
- character is ‘-‘ and negative flag is not set, set negative to -1
- character is ‘+’ and negative flag is not set, set negative to 1
- character is ‘-‘ or ‘+’ and negative flag is set, break out
- character is a character or ‘.’, break out
- character is a digit, set flag to true and store the digit in answer
- If digit is found and the flag is true:
- character is a digit, store the digit in answer
- If the limit is reached, set the corresponding side limit as the final answer
- If the character is anything other than digit, break out.
- Print the final value of the answer.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int myatoi(string s)
{
int left = (-1) * pow (2, 31);
int right = pow (2, 31) - 1;
long ans = 0, neg = 0, flag = false ;
for ( int i = 0; i < s.length(); i++) {
if (s[i] == ' ' ) {
if (flag)
break ;
else
continue ;
}
else if (s[i] == '-'
|| s[i] == '+' ) {
if (neg != 0)
break ;
else if (s[i] == '-'
&& neg == 0) {
neg = -1;
flag = true ;
}
else if (s[i] == '+'
&& neg == 0) {
neg = 1;
flag = true ;
}
}
else if ((s[i] == '.'
|| !(s[i] - '0' >= 0
&& s[i] - '0' < 10)))
break ;
else if (s[i] - '0' >= 0
&& s[i] - '0' < 10) {
flag = true ;
neg = neg == 0 ? 1 : neg;
if (!(ans < left || ans > right
|| ans * 10 + (s[i] - '0' )
< left
|| ans * 10 + (s[i] - '0' )
> right))
ans = ans * 10 + (s[i] - '0' );
else
ans = neg == -1 ? left : right;
}
}
return ans * neg;
}
int main()
{
string str = " -2" ;
cout << myatoi(str);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static long myatoi(String s)
{
int left = ( int ) Math.pow( 2 , 31 );
left *= - 1 ;
int right = ( int ) Math.pow( 2 , 31 ) - 1 ;
long ans = 0 , neg = 0 ;
Boolean flag = false ;
for ( int i = 0 ; i < s.length(); i++) {
if (s.charAt(i) == ' ' ) {
if (flag == true )
break ;
else
continue ;
}
else if (s.charAt(i) == '-'
|| s.charAt(i) == '+' ) {
if (neg != 0 )
break ;
else if (s.charAt(i) == '-'
&& neg == 0 ) {
neg = - 1 ;
flag = true ;
}
else if (s.charAt(i) == '+'
&& neg == 0 ) {
neg = 1 ;
flag = true ;
}
}
else if ((s.charAt(i) == '.'
|| !(s.charAt(i) - '0' >= 0
&& s.charAt(i) - '0' < 10 )))
break ;
else if (s.charAt(i) - '0' >= 0
&& s.charAt(i) - '0' < 10 ) {
flag = true ;
neg = neg == 0 ? 1 : neg;
if (!(ans < left || ans > right
|| ans * 10 + (s.charAt(i) - '0' )
< left
|| ans * 10 + (s.charAt(i) - '0' )
> right))
ans = ans * 10 + (s.charAt(i) - '0' );
else
ans = neg == - 1 ? left : right;
}
}
return ans * neg;
}
public static void main (String[] args) {
String str = " -2" ;
System.out.print(myatoi(str));
}
}
|
Python3
def myatoi(s):
left = ( - 1 ) * ( 2 * * 31 )
right = ( 2 * * 31 ) - 1
ans = 0
neg = 0
flag = False
for i in range ( len (s)):
if (s[i] = = ' ' ):
if (flag):
break
else :
continue
elif (s[i] = = '-' or s[i] = = '+' ):
if (neg ! = 0 ):
break
elif (s[i] = = '-' and neg = = 0 ):
neg = - 1
flag = True
elif (s[i] = = '+' and neg = = 0 ):
neg = 1
flag = True
elif ((s[i] = = '.' or not ( ord (s[i]) - ord ( '0' ) > = 0 and ord (s[i]) - ord ( '0' ) < 10 ))):
break
elif ( ord (s[i]) - ord ( '0' ) > = 0 and ord (s[i]) - ord ( '0' ) < 10 ):
flag = True
neg = 1 if neg = = 0 else neg
if ( not (ans < left or ans > right
or ans * 10 + ( ord (s[i]) - ord ( '0' ))
< left
or ans * 10 + ( ord (s[i]) - ord ( '0' ))
> right)):
ans = ans * 10 + ( ord (s[i]) - ord ( '0' ))
else :
ans = left if neg = = - 1 else right
return ans * neg
str = " -2"
print (myatoi( str ))
|
C#
using System;
class GFG {
static long myatoi( string s)
{
int left = ( int ) Math.Pow(2, 31);
left *= -1;
int right = ( int ) Math.Pow(2, 31) - 1;
long ans = 0, neg = 0;
bool flag = false ;
for ( int i = 0; i < s.Length; i++) {
if (s[i] == ' ' ) {
if (flag == true )
break ;
else
continue ;
}
else if (s[i] == '-'
|| s[i] == '+' ) {
if (neg != 0)
break ;
else if (s[i] == '-'
&& neg == 0) {
neg = -1;
flag = true ;
}
else if (s[i] == '+'
&& neg == 0) {
neg = 1;
flag = true ;
}
}
else if ((s[i] == '.'
|| !(s[i] - '0' >= 0
&& s[i] - '0' < 10)))
break ;
else if (s[i] - '0' >= 0
&& s[i] - '0' < 10) {
flag = true ;
neg = neg == 0 ? 1 : neg;
if (!(ans < left || ans > right
|| ans * 10 + (s[i] - '0' )
< left
|| ans * 10 + (s[i] - '0' )
> right))
ans = ans * 10 + (s[i] - '0' );
else
ans = neg == -1 ? left : right;
}
}
return ans * neg;
}
public static void Main () {
string str = " -2" ;
Console.Write(myatoi(str));
}
}
|
Javascript
<script>
function myatoi(s) {
let left = (-1) * Math.pow(2, 31);
let right = Math.pow(2, 31) - 1;
let ans = 0, neg = 0, flag = false ;
for (let i = 0; i < s.length; i++) {
if (s[i] == ' ' ) {
if (flag)
break ;
else
continue ;
}
else if (s[i] == '-'
|| s[i] == '+' ) {
if (neg != 0)
break ;
else if (s[i] == '-'
&& neg == 0) {
neg = -1;
flag = true ;
}
else if (s[i] == '+'
&& neg == 0) {
neg = 1;
flag = true ;
}
}
else if ((s[i] == '.'
|| !(s[i].charCodeAt(0) - '0' .charCodeAt(0) >= 0
&& s[i].charCodeAt(0) - '0' .charCodeAt(0) < 10)))
break ;
else if (s[i].charCodeAt(0) - '0' .charCodeAt(0) >= 0
&& s[i].charCodeAt(0) - '0' .charCodeAt(0) < 10) {
flag = true ;
neg = neg == 0 ? 1 : neg;
if (!(ans < left || ans > right
|| ans * 10 + (s[i].charCodeAt(0) - '0' .charCodeAt(0))
< left
|| ans * 10 + (s[i].charCodeAt(0) - '0' .charCodeAt(0))
> right))
ans = ans * 10 + (s[i].charCodeAt(0) - '0' .charCodeAt(0));
else
ans = neg == -1 ? left : right;
}
}
return ans * neg;
}
let str = " -2" ;
document.write(myatoi(str));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
31 Jan, 2022
Like Article
Save Article