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 }
  • 相关阅读:
    建设Kubernetes生产环境的16条建议
    深度长文:深入理解Ceph存储架构
    10个最危险的Linux命令,希望你牢记在心
    完美排查入侵者的 10 个方法和 1 个解决思路
    基于Docker&Kubernetes构建PaaS平台基础知识梳理
    Linux入门进阶
    (七)服务接口调用-OpenFeign
    (六)服务调用负载均衡-Ribbon
    (五)Eureka替换方案-Consul
    (四)Eureka替换方案-Zookeeper
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4034183.html
Copyright © 2011-2022 走看看