iOS面试题解析前端让前端飞

《前端面试题》- 编程题- 数字交换一次得到最大的数字

2021-03-02  本文已影响0人  张中华

输入一个数字(整数),交换两位数字,最多交换一次,输出可以得到的最大的数字,如输入:1234交换1,4后,得到4231;

        function exchangeNum(num) {
            let result;
            if (num > 0 && Number.isInteger(num)) {
                const numArr = [...num.toString()];
                const startPostion = findChangePosition(numArr);
                const notNeedChange = numArr.slice(0, startPostion);

                const needChange = numArr.slice(startPostion);
                const maxNum = findMax(needChange);
                const maxIndex = needChange.lastIndexOf(maxNum);

                [needChange[0], needChange[maxIndex]] = [needChange[maxIndex], needChange[0]]
                result = Number(notNeedChange.concat(needChange).join(''));
            }

            return result;
        }


        function findChangePosition(numArr) {
            const maxNum = findMax(numArr);
            let startPosition = 0;
            for (let i = 0; i < numArr.length; i++) {
                startPosition = i;
                if (maxNum !== numArr[i]) {
                    break;
                }
            }
            return startPosition;
        }

        function findMax(arr) {
            return Math.max.apply(null, arr).toString();
        }

        function findMin(arr) {
            return Math.min.apply(null, arr).toString();
        }

        // Test data
        console.log(exchangeNum(1234));
        console.log(exchangeNum(4321));
        console.log(exchangeNum(14234));
        console.log(exchangeNum(41324));
上一篇下一篇

猜你喜欢

热点阅读