把字符串转换成整数

 //leetcode8

public class Solution {

   public int myAtoi(String str) {
       int index = 0; 
       int sign = 1; 
       int total = 0;
      //1. Empty string 
       if(str.length() == 0) {
          return 0;
       }
       //2. Remove Spaces  去掉string开头处的空格
       while (str.charAt(index) == ' ' && index < str.length())
          index++;
       //3. Handle signs 如果string开头是+,最后结果为正
       if(str.charAt(index) == '+' || str.charAt(index) == '-') {
          sign = str.charAt(index) == '+' ? 1 : -1;
          index++; //要记住判断完后,index加1
       }
       //4. Convert number and avoid overflow
       while(index < str.length()) {
          int digit = str.charAt(index) - '0'; //记住要减'0',否则str等于111,str.charAt(0)是1,1的ascii码是49 
          if(digit < 0 || digit > 9) 
             break;
       //check if total will be overflow after 10 times and add digit  判断是不是overflow,如果满足if条件,就会大于2^31-1,是的话就取到 Integer.MAX_VALUE
       if(Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit)
          return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
       total = 10 * total + digit;
       index ++;
   }
   return total * sign;
   }
}
posted @   MarkLeeBYR  阅读(92)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示