Open In App

Find the valid integer from given String

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the valid integer
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;
}
 
// Driver code
int main()
{
    string str = "    -2";
    cout << myatoi(str);
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to find the valid integer
  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;
  }
 
  // Driver code
  public static void main (String[] args) {
    String str = "    -2";
    System.out.print(myatoi(str));
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3




# Python code for the above approach
 
# Function to find the valid integer
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
 
# Driver code
str = "    -2"
print(myatoi(str))
 
# This code is contributed by Saurabh Jaiswal


C#




// C# program for the above approach
using System;
class GFG {
 
  // Function to find the valid integer
  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;
  }
 
  // Driver code
  public static void Main () {
    string str = "    -2";
    Console.Write(myatoi(str));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to find the valid integer
       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;
       }
 
       // Driver code
       let str = "    -2";
       document.write(myatoi(str));
 
      // This code is contributed by Potta Lokesh
   </script>


 
 

Output

-2

 

Time Complexity: O(N)
Auxiliary Space: O(1)

 



Last Updated : 31 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads