📌  相关文章
📜  从给定的字符串中找到有效的整数

📅  最后修改于: 2022-05-13 01:56:06.565000             🧑  作者: Mango

从给定的字符串中找到有效的整数

给定一个大小为N的字符串str ,包含' ' , '.''-''+'['0'-'9'] ,任务是从这个字符串中找到有效的整数。
如果遵循以下规则,则整数被认为是有效的:

  • 如果str有前导空格,请忽略它们。
  • 第一个有效字符应该是 '-'、'+' 或 ['0'-'9']
  • 如果没有给出符号,则将整数视为正数
  • 如果整数前还有其他无效字符,则打印 0。
  • 如果整数后面有无效字符,则打印整数
  • 如果数字是十进制数,则将其转换为整数
  • 忽略任何前导 0
  • 使整数在 [-2^31, 2^31-1] 范围内,如果不是,则打印相应的限制。
  • 读入下一个字符,直到到达下一个非数字字符或输入结尾。字符串的其余部分被忽略。

例子:

方法:创建一个变量来保存最终整数并使其变长,直到限制可能被打破。

逐个字符遍历字符串,并为找到的第字符数字保留标志和负数:

  • 如果还没有找到数字,并且:
    • 字符是空格,忽略
    • 字符为 '-' 且未设置负标志,将负标志设置为 -1
    • 字符为“+”且未设置负标志,将负标志设置为 1
    • 字符为“-”或“+”并且设置了负标志,中断
    • 字符是一个字符或'.',break out
    • 字符是一个数字,将 flag 设置为 true 并将数字存储在 answer
  • 如果找到 digit 并且标志为真:
    • 字符是数字,将数字存储在答案中
    • 如果达到限制,则设置相应的边限制作为最终答案
    • 如果字符不是数字,则中断。
  • 打印答案的最终值。

下面是上述方法的实现。

C++
// C++ code to implement the approach
#include 
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



输出
-2

时间复杂度: O(N)
辅助空间: O(1)