面试题B1: 字符串转数字

2019-10-09  本文已影响0人  mark_x

package cn.zxy.interview;

/**
 * 因为最近主要在补基础和实战项目, 难得抽时间看算法, 不过一天至少要一道吧, 要不然就越拖越坚持不下来了
 * B类问题是剑指Offer中涉及但是没有单列为面试题的, 在这里进行一下整理和实现
 *
 * 问题: 字符数字转整型, 如"123"-->123, 基本上相当于Integer.Parse()
 * 分析: 从字符串最后一位开始, 每位的字符就是权重, weight*10^i
 * 每处理完一位temp*10, 最后一位每个数字*1 依次*10  *100 ...
 * 最后判断字符串第一个数组是不是"-"
 */

public class B01_IntegerParse {
    public static int String2Int(String str) {
        int result = 0;
        int temp = 1;

        for (int i = str.length() - 1; i > 0; i--) {
            int num = str.charAt(i) - '0';
            result += num * temp;
            temp *= 10;
        }
        // 对第一位单独判断
        if(str.charAt(0) == '-'){
            result = -result;
        }else{
            result += (str.charAt(0) - '0') * temp;
        }

        return result;
    }


    public static void main(String[] args) {

        int num = String2Int("-3");
        System.out.println(num);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读