把字符串转换成整数

来源:互联网 发布:java string split n 编辑:程序博客网 时间:2024/06/05 22:59

题目描述

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。

思路:设置两个标志位 一个tag 为1表示是正数,为0表示是负数,一个index,为‘+’则index是1,为‘-’则index是-1,什么都没index是0

     再用一个result去接受所有的数,result  =result * 10 + aa;从第一个开始慢慢加起来,不过每次都要判断是否上下溢出,最后还换转换类型

代码如下:

public class Solution {    public int StrToInt(String str) {        if(str.length() == 0) return 0;             int tag = 0;             int start = 0;             if(str.charAt(0) == '+'){                   start = 1;                   tag  = 1;             }else  if(str.charAt(0) == '-'){                   start = 1;                   tag = 0;             }else{                   start = 0;                    tag = 1;             }              long result = 0;              for(int i = start;i<str.length();i++){                     char aa = str.charAt(i);                      if(aa >= '0' && aa <= '9'){                             result = result * 10 + (aa - '0');                         if(tag == 1 && result > Integer.MAX_VALUE){                             throw new RuntimeException("上溢出");                         }                         if(tag == 0 && result < Integer.MIN_VALUE){                             throw new RuntimeException("下溢出");                         }                      }else{                          return 0;                      }              }               if(tag == 0){                   return (int)(result * (-1));               }else{                   return (int)result;               }    }}


0 0