zoukankan      html  css  js  c++  java
  • [Leetcode] String to Integer (atoi)

    Implement atoi to convert a string to an integer.

    Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

    Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

    spoilers alert... click to show requirements for atoi.

    Requirements for atoi:

    The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

    The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

    If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

    If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

    Solution:

     1 public class Solution {
     2     public int atoi(String str) {
     3         str = str.trim();
     4         int length = str.length();
     5         if (length == 0)
     6             return 0;
     7         boolean minus = false;
     8         int i = 0;
     9         if (str.charAt(0) == '-') {
    10             minus = true;
    11             i++;
    12         } else if (str.charAt(0) == '+') {
    13             i++;
    14         }
    15         long num = 0l;
    16         long max = Integer.MAX_VALUE;
    17         long min = Integer.MIN_VALUE;
    18         for (; i < length; ++i) {
    19             char c = str.charAt(i);
    20             if (c >= '0' && c <= '9') {
    21                 num *= 10;
    22                 num += c - '0';
    23             } else {
    24                 break;
    25             }
    26             if (minus && 0 - num < min) {
    27                 return Integer.MIN_VALUE;
    28             } else if (!minus && num > max)
    29                 return Integer.MAX_VALUE;
    30         }
    31 
    32         return minus ? new Long(0 - num).intValue() : new Long(num).intValue();
    33     }
    34 }
  • 相关阅读:
    统计学习及监督学习概论(2)
    推荐系统(1)
    统计学习及监督学习概论(1)
    JavaScript学习08 Cookie对象
    JavaScript学习07 内置对象
    JavaScript学习06 JS事件对象
    JavaScript学习05 定时器
    JavaScript学习04 对象
    JavaScript学习03 JS函数
    JavaScript学习02 基础语法
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4034183.html
Copyright © 2011-2022 走看看