008字串轉換整數
阿新 • • 發佈:2020-08-07
寫在前面,參考的是力扣官網的解題思路,好懂和圖解
一、java程式碼
/* * @lc app=leetcode.cn id=8 lang=java * * [8] 字串轉換整數 (atoi) */ // @lc code=start class Solution { public int myAtoi(String str) { //字串轉換為陣列 char[] chars=str.toCharArray(); //陣列長度 int n=chars.length; //陣列下標 int idx=0; //去掉前導空格 while(idx<n&&chars[idx]==' '){ idx++; } //如果去掉前導空格後就到末尾了,則直接返回0 if(idx==n){ return 0; } //negative標記負號 boolean negative=false; //判斷第一個非空字元 //如果遇到負號則記錄下狀態 if(chars[idx]=='-'){ negative=true; idx++; //如果遇到正號,可以忽略 }else if(chars[idx]=='+'){ idx++; //其他符號,則直接返回0 }else if(!Character.isDigit(chars[idx])){ return 0; } //輸出的數,先定義為0 int ans=0; //Character.isDigit判斷是否為數字 while (idx<n&&Character.isDigit(chars[idx])){ //將字元數字轉換為數字'1'-'0'=1 int digit=chars[idx]-'0'; //也就是說會在某一步`ans*10+digit>Integer.MAX_VALUE` //`*10`和`+digit`都可能會越界,那麼只要把這些都移到右邊去就可以了 if(ans>(Integer.MAX_VALUE-digit)/10){ return negative?Integer.MIN_VALUE:Integer.MAX_VALUE; } //最基本的基本 ans=ans*10+digit; //下標自增 idx++; } return negative?-ans:ans; } } // @lc code=end
二、題解分析
做題思路
1、去掉前導空格
2、處理正負號
3、識別數字,注意越界的情況
程式碼解釋
1、這道題如果只是簡單的字串轉換整數的話,就是簡單的ans=ans*10+digit
2、但是這道題可能會超過integer的最大表示
3、也就是說會在某一步ans*10+digit>Integer.MAX_VALUE
-
*10
和+digit
都可能會越界,那麼只要把這些都移到右邊去就可以了 -
ans>(Integer.MAX_VALUE-digit)/10
就是越界