Find the Valid Integer from given String


In this problem, we need to extract the integer from the given string by following the rules in the problem statement. We can solve the problem by checking if the initial substring of the string follows each rule given for the valid integer value.

Problem statement – We have given string digits containing the numeric digits, ‘.’, ‘+’, and ‘-‘ characters. We need to extract the valid integer value from the given string.

Rules for valid integers

  • It should not contain the leading zeros and whitespaces.

  • The integer should either start with a sign or digits.

  • When any sign is not given, consider that integer is positive.

  • If the string contains a decimal part, extract the integer part from the string.

  • Print 0 if the string contains other characters except digits before the integer value.

  • Extract and print the integer value if the string contains other alphabetical digits after the integer value.\

  • The integer should be between -2147483647 and 2147483647. If not, print the limit value.

  • Extract the initial integer if the string contains other characters in the middle.

Sample examples

Input

digits = "+234567.4234"

Output

234567

Explanation – It has extracted the integer part from the decimal number. Also, the sign is ‘+’, so it has printed the positive number without a sign.

Input

digits = "-23324";

Output

-23324

Explanation – It has printed the decimal part of the number with the sign.

Input

digits = "   000122";

Output

122

Explanation – It has ignored the leading whitespaces and zeros.

Input

digits = "   000122";

Output

0

Explanation – The string contains other alphabetical characters before digits. So, it prints 0.

Approach 1

In this approach, we will check for leading whitespace, zeros, sign, etc. Also, we will manage the decimal part of the string. In short, we will find an integer value that follows all given rules.

Users can follow the below algorithm step by step.

Algorithm

Step 1 – Initialize the mini and maxi variables with minimum and maximum integer values.

Step 2 – Define the ‘final_int’ variable to store the integer value, the ‘sign’ variable to store the sign of the integer, and the ‘digitPresent’ variable to keep track of the number string containing the digits. The ‘digitPresent’ variable is useful to check if the string contains other characters at the start, white spaces in the middle, etc.

Step 3 – Start traversing the number string.

Step 4 – If the character at the ith index is whitespace, and ‘digitPresent’ is true, it means white space is in the middle of the integer. So, break the loop using the break keyword. Otherwise, use the ‘continue’ keyword to move to the next iteration if whitespace is in the starting.

Step 5 – If the ith character is ‘-‘ or ‘+’, follow the steps below.

Step 5.1 – If ‘sign’ is not zero, break the loop as ‘-‘ or ‘+’ is in the middle of the integer value.

Step 5.2 – If a character is ‘-‘, update the value of the ‘sign’ variable to -1, and update the ‘digitsPresent’ variable to true as the integer started.

Step 5.3 – If a character is ‘+’ update the ‘sign’ variable value to 1, and update the ‘digitPresent’ variable to true.

Step 6 – If the current character is ‘.’ or other characters, break the loop.

Step 7 – If an ith character is a digit between 0 and 9, follow the steps below.

Step 7.1 – Update the value of ‘digitPresent’ to true.

Step 7.2 – If the value of ‘sign’ is 0, update it to 1, as the string doesn’t contain any sign. So, we consider it positive by default. Otherwise, keep it as it is.

Step 7.3 – If final_int < mini / 10 || final_int > maxi / 10 || final_int * 10 + (digits[i] - '0') < mini || final_int * 10 + (digits[i] - '0') > maxi) is true, multiply final_int by 10, and add digit value. Otherwise, if the integer value exceeds the limit, assign mini or maxi according to the sign value.

Step 8 – Return the final_int*sign value.

Example

#include <iostream>
#include <cmath>
using namespace std;

int getValidInt(string digits) {
    // Get the minimum and maximum integer value
    int mini = (-1) * pow(2, 31);
    int maxi = pow(2, 31) - 1;
    // Variable initialization
    long final_int = 0;
    int sign = 0, digitPresent = false;
    // Traverse the string
    for (int i = 0; i < digits.length(); i++) {
        // Ignoring only leading white spaces
        if (digits[i] == ' ') {
            if (digitPresent)
                break;
            else
                continue;
        }
        // handling the sign
        else if (digits[i] == '-' || digits[i] == '+') {
            // Case 1 - The sign is in the middle of the string
            if (sign != 0)
                break;
            // Case 2 - The sign is at the start of the string
            else if (digits[i] == '-' && sign == 0) {
                sign = -1;
                digitPresent = true;
            } else if (digits[i] == '+' && sign == 0) {
                sign = 1;
                digitPresent = true;
            }
        }
         // handling other characters.
        // Removing decimal part
        else if ((digits[i] == '.' || !(digits[i] - '0' >= 0 && digits[i] - '0' < 10))) {
            break;
        }
        // Handling digits
        else if (digits[i] - '0' >= 0 && digits[i] - '0' < 10) {
            digitPresent = true;
            sign = sign == 0 ? 1 : sign;
            if (!(final_int < mini / 10 || final_int > maxi / 10 || final_int * 10 + (digits[i] - '0') < mini || final_int * 10 + (digits[i] - '0') > maxi)) {
                final_int = final_int * 10 + (digits[i] - '0'); 
            } else {
                final_int = sign == -1 ? mini : maxi;
                break;
            }
        }
    }
    return final_int * sign;
}
int main() {
    string digits = "  +234567.4234";
    cout << "The valid integer from the given string is - " << getValidInt(digits);
    return 0;
}

Output

The valid integer from the given string is - 234567

Time complexity – O(N) to extract the integer value.

Space complexity – O(1)

Programmers need to write the if-else statement in the same order as written in the above code. If they write in a different order, the code will sometimes give the wrong output. So, we can learn that it is also important to maintain the order of the if-else statement in some problems like this.

Updated on: 25-Aug-2023

61 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements