字符串转换成一个整数

题目描述

将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
package solution;

import java.util.Scanner;

public class StrToInt {
    public static void main(String[] args) {
        System.out.println(StrToInt(""));
    }

    public static int StrToInt(String str) {
        if (str == null || str=="" || str.length()==0)
            return 0;
        //1.先将字符串转换成字符数组
        char[] num = str.toCharArray();
        //2.对字符数组中的每一位进行判断
        int base = 1;
        if (num[0] == '-' && num.length > 1) {
            base = -1;
        } else if (num[0] == '+' && num.length > 1) {
            base = 1;
        } else if (!((num[0] >= '0') && (num[0] <= '9'))) {
            return 0;
        }
        int sum = 0;
        int count = 0;
        for (int i = num.length - 1; i > 0; i--) {
            if(num[i] >= '0' && num[i] <= '9'){
                sum += base * Integer.parseInt(String.valueOf(num[i])) * Math.pow(10, count);
                count++;
            }else{
                return 0;
            }
        }
        if(num[0] >= '0' && num[0] <= '9'){
            sum += base * Integer.parseInt(String.valueOf(num[0])) * Math.pow(10, count);
        }
        return (int)sum;
    }

}

猜你喜欢

转载自www.cnblogs.com/ustc-anmin/p/11396458.html