亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

[leetcode]經典算法題- 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.

思路分析:
  • 首先判断为空,返回0
  • 考虑前面是空格,使用trim()去掉,然后判断长度是否为0,是的话,返回0
  • 判断第一个字符是不是+和-,设置变量sign记录。
  • 循环取得字符串的数字,考虑字符串中有非数字,遇到就退出,保留前面的数字
  • 考虑溢出的情况,溢出返回Integer的最大值和最小值
代码实现:
public class Solution {
    public int myAtoi(String str) {
        //首先判断空值
        if(str == null){
            return 0;
        }
        //去掉空格的情况
        str = str.trim();
        if(str.length() == 0){
            return 0;
        }
        int sign = 1;
        int index = 0;
        if(str.charAt(index) == '+'){
            index++;
        }else if(str.charAt(index) == '-'){
            index++;
            sign = -1;
        }
        //取得数字部分,遇到溢出和非数字退出
        long number = 0;
        for(;index < str.length();index++){
            if(str.charAt(index) < '0'  str.charAt(index) > '9'){
                break;
            }
            number = number *10 + (str.charAt(index) - '0');
            if(number >= Integer.MAX_VALUE){
                break;
            }
        }
        if(number * sign >= Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        if(number * sign <= Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }
        return (int)number*sign;
    }
}
點擊查看更多內容
17人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
移動開發工程師
手記
粉絲
424
獲贊與收藏
5663

關注作者,訂閱最新文章

閱讀免費教程

感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消