• 8. String to Integer (atoi) Java Solutin


    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.

    Update (2015-02-10):
    The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

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

    Subscribe to see which companies asked this question

    Show Tags
    Show Similar Problems
     
    题意: 

    实现 atoi,将字符串转化为整数。


    注意考虑所有可能的情况。



    算法分析: 

    1. 
    先去掉多余的空格字符,从第一个非空格字符开始。


    2. 
    按顺序读数字,如果出现下面三种情况则结束:


    2.1 
    异常字符出现(异常字符跳过不计)。


    2.2 
    数字越界(返回最接近的整数)。


    2.3 
    字符串结束

     1 public class Solution {
     2     public int myAtoi(String str) {
     3         if(str == null) return 0;
     4         str = str.trim();
     5         if(str.length() == 0) return 0;
     6         Boolean isNex = false;
     7         int i = 0;
     8         if(str.charAt(0) == '+' || str.charAt(0) == '-'){
     9             i++;
    10             if(str.charAt(0) == '-')
    11                 isNex = true;
    12         }
    13         long result = 0;//若定义为int,边界值将会溢出。
    14         for(;i<str.length();i++){
    15             if(str.charAt(i) > '9' || str.charAt(i) < '0')
    16                 break;
    17             result = result*10 + str.charAt(i) - '0';
    18             if(result > Integer.MAX_VALUE && !isNex)
    19                 return Integer.MAX_VALUE;
    20             if(-result < Integer.MIN_VALUE && isNex)
    21                 return Integer.MIN_VALUE;
    22         }
    23         if(!isNex) return (int) result;
    24         else result = -result;
    25         return (int)result;
    26     }
    27 }
  • 相关阅读:
    【转】linux之fsck命令
    【转】linux之mkfs/mke2fs格式化
    【转】linux_fdisk命令详解
    【转】linux之ln命令
    [转]linux的du和df命令
    [转]Linux之type命令
    [转]Linux下which、whereis、locate、find 命令的区别
    [转]Linux的chattr与lsattr命令详解
    get 与post 的接收传值方式
    在asp.net前台页面中引入命名空间 和连接数据库
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5387048.html
Copyright © 2020-2023  润新知