zoukankan      html  css  js  c++  java
  • 8. String to Integer (atoi)

    一、题目

      1、审题:

        

      2、分析:

        截取所给字符串的最前面的数字部分,否则为0;

    二、解答

      1、分析: 

        a、字符串去前后空格;

        b、判断正负号;

        c、依次截取字符,判断是否为数字,进行组装;

    class Solution {
        public int myAtoi(String str) {
    
            str = str.trim();
            int len = str.length();
            if(str == null || len == 0)
                return 0;
    
            int index = 0;
            boolean isNegative = false;
            if(str.charAt(0) == '-') {
                isNegative = true;
                index++;
            }
            else if(str.charAt(0) == '+') {
                index++;
            }
    
            long result = 0;
            for (  ; index < len; index++) {
                int num = str.charAt(index) - '0';
                if(num < 0 || num > 9) break;
    
                if(!isNegative) {    // 在里边判断可以避免, result 超出 Long 范围溢出的情况
                    result = result * 10 + num;
                    if(result > Integer.MAX_VALUE)
                        return Integer.MAX_VALUE;
                }
                else {
                    result = result * 10 - num;
                    if(result < Integer.MIN_VALUE)
                        return Integer.MIN_VALUE;
                }
            }
    
            return (int)result;
        }
    }
  • 相关阅读:
    googleMap JsAPI
    格式化Json代码
    baidu map JSAPI
    ajaxFileUpload与KindEditor
    Intent 意图
    初识Android
    Android环境搭建
    Android入门知识梳理
    网页版计算器
    使用socket实现简单的聊天功能
  • 原文地址:https://www.cnblogs.com/skillking/p/9399357.html
Copyright © 2011-2022 走看看