LeetCode 第 A 题:字符串转 double

2021-07-06  本文已影响0人  放开那个BUG

1、前言

给定一个字符串,将字符串转换为 double 类型的数字,不能用 jdk 自带的工具。

2、思路

这道题的思路其实很简单,将字符串分为两个部分,整数与小数部分。我们先求整数部分,求完后再求小数部分。所以,做这种题的思路是,先求整数,再求小数,然后完善剩下的格式的问题。

3、代码

public class QA_StringToDouble {


    public double stringToDouble(String num) throws Exception {
        double sumA = 0, sumB = 0;

        int first = num.charAt(0);
        if(first != '+' && first != '-' && (first < '0' || first > '9')){
            throw new Exception("格式不正确");
        }

        int i = 0;
        boolean positive = true;
        if(first == '-'){
            positive = false;
            i++;
        }else {
            i++;
        }


        for (; i < num.length(); i++) {
            if(num.charAt(i) != '.' && (num.charAt(i) < '0' || num.charAt(i) > '9')){
                throw new Exception("格式不正确");
            }
            if(num.charAt(i) == '.'){
                i++;
                break;
            }
            sumA = 10 * sumA + (num.charAt(i) - '0');
        }

        // 这边默认 i 是小数的后一位
//        int i = 1;
//        for(; i < num.length(); i++){
//            if(num.charAt(i) < '0' || num.charAt(i) > '9'){
//                throw new Exception("格式不正确");
//            }
//
//            j *= 10;
//            sumB = 10 * sumB + (num.charAt(i) - '0');
//        }
        int j = num.length() - 1;
        for(; j >= i; j--){
            if(num.charAt(j) < '0' || num.charAt(j) > '9'){
                throw new Exception("格式不正确");
            }

            sumB = (sumB + (num.charAt(j) - '0')) * 0.1;
        }


        return positive ? sumA + sumB : (-1) * (sumA + sumB);
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new QA_StringToDouble().stringToDouble("+156.788999999999"));
    }
}
上一篇下一篇

猜你喜欢

热点阅读