题解 | #求解立方根#

求解立方根

https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    while ((line = await readline())) {
        //  二分法
        let num = +line;
        let count = 1;
        let max;
        let min ;
        if (num > 0) {
            count = 1;
            while (count * count * count <= num) {
                count++;
            }
            max=count;
            min = count - 1;
        } else {
            count = 0;
            while (count * count * count >= num) {
                count--;
            }
            min=count;
            max = count +1;
        }

        while (max - min > 0.1) {
            let mid = ((max + min) / 2).toFixed(1);
            if (mid * mid * mid < num) {
                min = +mid + 0.01;
            } else {
                max = mid - 0.01;
            }
            // console.log(max, min, mid);
        }
        // console.log(max,min)

        let disMax = Math.abs(max * max * max - num);
        let disMin = Math.abs(min * min * min - num);
        let res = disMax > disMin ? min : max;
        console.log(res.toFixed(1));
        // console.log(((max+min)/2).toFixed(1))

        //     let a = parseInt(tokens[0]);
        //     let b = parseInt(tokens[1]);
        //     console.log(a + b);
    }
})();

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务