把字符串转换成整数

题目:
题目
需要考虑的是,这个数带不带符号,符号是"+" 还是”-“,可以通过字符串的第一个字符,使用flag记录一下这个符号,若没有符号,则从字符串头到字符串尾依次遍历,若有符号,则总第二个字符开始遍历,注意:在最后输出结果时,根据flag的记录,将符号恢复(若为”+“,则不用恢复)

实现代码如下:

package cn.strtoint;

/**
 * @program: algorithm_learn
 * @description: 把字符串转换成整数
 * @author: Mr.Luo
 * @create: 2020-06-11 14:12
 */
public class Main {
    public static int StrToInt(String str){
        if (str.length() == 0){
            return 0;
        }
        char[] chars = str.toCharArray();
        //判断是否存在符号位
        int flag = 0;
        if (chars[0] == '+'){
            flag = 1;
        }else if (chars[0] == '-'){
            flag = 2;
        }

        int start = flag > 0 ? 1 : 0;
        //保存结果
        int res = 0;
        for (int i = start; i < chars.length; i++) {
            if (Character.isDigit(chars[i])){
                int temp = chars[i] - '0';
                res = res * 10 + temp;
            }else {
                return 0;
            }
        }
        return flag == 2 ? -res : res;

    }

    public static void main(String[] args) {
        String s = "-12312312";
        System.out.println("使用库函数转换:" + Integer.valueOf(s));
        System.out.println("使用自己写的方法转换:" + StrToInt(s));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值