zoukankan      html  css  js  c++  java
  • String to Integer

    String to Integer

    问题:

    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.

    思路:

      只是需要考虑的corner case多一些,思路很简单

    我的代码:

    public class Solution {
        public int myAtoi(String str) {
            if(str==null || str.length()==0 || str.trim().length()==0)  return 0;
            str = str.trim();
            boolean isPlus = true;
            if(str.charAt(0) == '-')
            {
                isPlus = false;
                str = str.substring(1);
            }
            else
            {
                if(str.charAt(0) == '+')
                    str = str.substring(1);
            }
            long rst = 0;
            for(int i=0; i<str.length(); i++)
            {
                char c = str.charAt(i);
                if(isValidNum(c))
                {
                    rst = rst*10 + (c-'0');
                    long tmp = (isPlus ? rst : rst*-1);
                    if(tmp>Integer.MAX_VALUE)   return Integer.MAX_VALUE;
                    if(tmp<Integer.MIN_VALUE)   return Integer.MIN_VALUE;
                }
                else 
                    break;
            }
            rst = (isPlus ? rst : rst*-1);
            return (int)rst;
        }
        public boolean isValidNum(char c)
        {
            return c<='9' && c>='0' ? true : false; 
        }
    
    }
    View Code
  • 相关阅读:
    HASH算法介绍
    windowsOracle19C安装
    Oracle快照控制文件理解
    Swap空间扩展
    OracleDBA职责—备份与恢复技术—RMAN4
    OI回忆录
    HEOI2020(NEW)
    HEOI2020
    省选前奇怪的心情减少了
    $Mom$
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4462148.html
Copyright © 2011-2022 走看看