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;
            }
        }
    }
  • 相关阅读:
    kvm虚拟化存储管理
    k8s集群部署
    docker版的zabbix部署
    docker进阶——数据管理与网络
    docker基础
    ceph对接openstack环境
    java命令--jmap命令使用
    JVM性能分析工具jstack介绍
    SkipList跳表基本原理
    NIO之Channel、Buffer
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506900.html
Copyright © 2011-2022 走看看