题解 | #把字符串转换成整数#

把字符串转换成整数

http://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e

import java.util.*;
import java.lang.*;
public class Solution {
    public int StrToInt(String str) {
        if(str==""||str.length()==0) return 0;
        if(str.length()==1&&str.charAt(0)<48)
            return 0;
        if(str.length()==1&&str.charAt(0)>57)
            return 0;
        long sum =0 ;
        int flag=0;
        for(int i=0;i<str.length();i++){
            if(48<=str.charAt(i)&&str.charAt(i)<=57){
                sum+=(str.charAt(i)-48)*Math.pow(10,str.length()-1-i);
            }else{
                if(str.charAt(0)=='+'||str.charAt(0)=='-'){
                    flag=(str.charAt(0)=='+')?1:-1;
                }else{
                    return 0;
                }
            }
        }
        if(flag!=0)sum =flag*sum;
        if(sum<Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }
        else if(sum>Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        else{
            return (int)sum;
        }
    }
}
全部评论

相关推荐

快点约我面试吧
投递百度等公司10个岗位
点赞 评论 收藏
分享
06-07 17:17
嘉兴学院 教师
心爱的idea:你孩
点赞 评论 收藏
分享
投递拓竹科技等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务