zoukankan      html  css  js  c++  java
  • 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.

    public class Solution {
        public int atoi(String str) {
            if (str==null || str.length()==0) {
                return 0;
            }
            //正负号 true是正 false是负
            boolean flag = true;
            int result = 0;
            str = str.trim();
            if (str.charAt(0)=='-') {
                flag = false;
                str = str.substring(1, str.length());
            }
            if (str.charAt(0)=='+') {
                str = str.substring(1, str.length());
            }
            String newstr = new String();
            for (int i=0;i<str.length();i++) {
                if (str.charAt(i)<'0'||str.charAt(i)>'9') {
                    break;
                }
                newstr += String.valueOf(str.charAt(i));
            }
            for (int i=0;i<newstr.length();i++) {
                char c = newstr.charAt(newstr.length()-1-i);
                if (result==0 && c=='0') {
                    continue;
                }
                if (c<'0'||c>'9') {
                    return result;
                }
                int temp = (int)Math.pow(10,i);
                //判断溢出
                if (Integer.MAX_VALUE -  (c-'0')*temp >= result ) {
                    result += (c-'0')*temp;
                } else {
                    return flag ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
            }
            if (flag) {
                return result;
            } else {
                return 0-result;
            }
        }
    }
  • 相关阅读:
    《鱼嘤嘤小分队》第一次作业:项目选题
    第一次博客作业
    csp 201709-2 优先队列模拟
    csp 201403-2
    csp 201809-2 买菜
    JavaScript中伪协议
    修改placeholder的样式
    jQuery对象与DOM对象之间的转换方法
    a的样式
    Guid.NewGuid() 和 new Guid()的区别
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506900.html
Copyright © 2011-2022 走看看