实现string 转int

import java.util.regex.Pattern;


public class StringtoInt {
   public static void main(String[] args) {
  int i;
try {
i = method("2147483647");  
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
  
   }
//将字符串转为数字
public static int method(String s) throws Exception{
int i = s.length();
if (0==i) {
throw new MyNumException(s+"不是数字");
}else if (1==i) {
Pattern pattern = Pattern.compile("[0-9]");
if(!pattern.matcher(s).matches()){
  throw new MyNumException(s+"不是数字");
}
return s.charAt(0)-48;
}else if (i>1) {
 //判断是否是数字
Pattern pattern = Pattern.compile("[0-9]*");
if(!pattern.matcher(s.substring(1)).matches()){
  throw new MyNumException(s+"不是数字");
}
if ("-".equals(s.charAt(0)+"")) {
//负  
if (s.length()==11&&(s.substring(1).compareTo("2147483648"))==0) { //处理边界值
return -2147483648;
}
return -toNumber(s.substring(1),false);
}else if ("+".equals(s.charAt(0)+"")) {
//正数
return +toNumber(s.substring(1),true);
}else {
//无符号数
if(!pattern.matcher(s).matches()){
  throw new MyNumException(s+"不是数字");
}
return toNumber(s,true);
}
}
return 0;
}
//转换数字,范围0-2147483647
public  static int  toNumber(String s,boolean flag)  {//正整数
   //判断范围   -2^31   2^31-1   -2147483648   2147483647
 if (flag) {
//非负
 if (s.length()>10) {
 throw new  MyNumException(s+"范围超过");
 } else if (s.length()==10&&(s.compareTo("2147483647"))>0) {
throw new  MyNumException(s+"范围超过");
 }
 }else{
//负数
 if (s.length()>10) {
 throw new  MyNumException(s+"范围超过");
 } else if (s.length()==10&&(s.compareTo("2147483648"))>0) {
throw new  MyNumException("-"+s+"范围超过");
 }
 }
int result =0;
char[] array = s.toCharArray();
for (int j = 0; j < array.length; j++) {
result+=Math.pow(10.0, s.length()-1-j)*(array[j]-48);//48  '0'
}
return result;
   }
}




class MyNumException extends RuntimeException {


private static final long serialVersionUID = 1L;


public MyNumException() {
super();
}
public MyNumException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}


public MyNumException(String message, Throwable cause) {
super(message, cause);
}


public MyNumException(String message) {
super(message);
}


public MyNumException(Throwable cause) {
super(cause);
}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值