天天看点

将字符串转换为数字

将字符串转换为数字
public class Solution {
    public int StrToInt(String str) {
          if(str==null||str.length()==)
             return ;

          int count=;
          boolean tag=true;
          if(str.charAt()!='-'&&str.charAt()!='+'&&
            (str.charAt()<||str.charAt()>||str.charAt()=='0'))
          {
             return ;
          }
          if(str.charAt()=='-') //第一个符号为负号
          {
              tag=false;
          }

          if(str.charAt()!='+'&&tag)  //第一个符号为数字
             count=(str.charAt()-)*(int)Math.pow(,str.length()-);
          for(int i=;i!=str.length();i++)
          {
               if(str.charAt(i)>=&&str.charAt(i)<=)
               {
                      count+=(str.charAt(i)-)*(int)Math.pow(,str.length()-i-);
               }else{

                  return ;
               }

          }
          if(!tag)
          {
              count*=-;
          }

           return count;
    }

    public static void main(String[]args){
         //System.out.println("Hello");
           Solution s=new Solution();

           System.out.println(s.StrToInt("+2147483647"));
    }
}
           
将字符串转换为数字