每日一道算法題 - KaprekarsConstant(hard-1)

雖然都是很簡單的算法,每一個都只需5分鐘左右,但寫起來總會遇到不一樣的小問題,但願你們能跟我一塊兒天天進步一點點。
更多的小算法練習,能夠查看個人文章。git

規則

Using the JavaScript language, have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits. Your program should perform the following routine on the number: Arrange the digits in descending order and in ascending order (adding zeroes to fit it to a 4-digit number), and subtract the smaller number from the bigger number. Then repeat the previous step. Performing this routine will always cause you to reach a fixed number: 6174. Then performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174). Your program should return the number of times this routine must be performed until 6174 is reached. For example: if num is 3524 your program should return 3 because of the following steps: (1) 5432 - 2345 = 3087, (2) 8730 - 0378 = 8352, (3) 8532 - 2358 = 6174. 算法

使用JavaScript語言,讓函數KaprekarsConstant(num)獲取 傳遞的num參數,該參數將是一個4位數字,至少有兩個不一樣的數字。
按降序和升序排列數字(添加零以使其適合4位數字),用較大的數字去較小的數字。
而後重複上一步,直到相減結果等於固定數字:6174,返回該程序必須執行的次數。
例如:若是傳入的參數爲3524,你的程序應該返回3,即該程序必須執行3次才能獲得6174的結果。
由於如下步驟:(1)5432 - 2345 = 3087,(2)8730 - 0378 = 8352,(3)8532 - 2358 = 6174.數組

function KaprekarsConstant(num) { 

  // code goes here  
  return num; 
}
   
// keep this function call here 
KaprekarsConstant(3524);

測試用例

Input:2111
Output:5

Input:9831
Output:7

my code

function KaprekarsConstant(num) {
  var count = 0
  while (true) {
    var maxNum = num
      .toString()
      .split('')
      .sort((item1, item2) => item2 - item1)
      .join('')
    maxNum = Number(maxNum)

    var minNum = num
      .toString()
      .split('')
      .sort()
      .join('')
    minNum = Number(minNum)

    num = '0000' + (maxNum - minNum)
    num = num.substr(-4)
    count++

    if (num == 6174 || num == 0) break
  }

  return count
}

other code

code-1

function KaprekarsConstant(num) {
    const KAP = 6174;
    var count = 0;
    while (true) {
        var num = evaluator(num)
        if (num === true) {
            return count;
        }
    }

    function evaluator(num) {
        count++
        console.log('count', count);
        var minNumArr = num.toString().split('').sort();
        var maxNumArr = minNumArr.slice(0).reverse();
        var littleNum = parseInt(minNumArr.join(''), 10);
        var bigNum = parseInt(maxNumArr.join(''), 10);
        while (bigNum < 1000) {
            bigNum = bigNum * 10;
        }

        return bigNum - littleNum === KAP ? true : bigNum - littleNum;
    }
}

code-2

function KaprekarsConstant(num) {
  var count = 0;
  while (num != 6174) {
    count += 1;
    var numArr = num.toString().split('');
    while (d.length < 4) {
      numArr.push('0');
    }
    var smaller = numArr.sort().join('');
    var bigger = numArr.reverse().join('');
    num = bigger - smaller;
  }
  return count;
}

code-3

function KaprekarsConstant(num) { 

    let count = 0;
    while (num != 6174) {
        let numArray = num.toString().split('').sort();
        
        let ascending = parseInt(numArray.join(''));
        let descending = parseInt(numArray.reverse().join(''));
        
        while (descending.toString().length < 4) {
            descending *= 10;
        }
        
        num = Math.abs(ascending - descending);

        count++;
        if (count > 999) break;  // failover
    }

    return count;
}

思路

我的思路:閉包

  1. 本想使用遞歸去解決,代碼量會更少更優雅,而後發現須要計算執行的次數,因此才使用while去遍歷執行(其實使用閉包也能夠解決,無奈題目調用就是KaprekarsConstant(xxxx)
  2. 先把數字轉成字符串再轉數組,使用數組升降排序拿到最大最小值,相減以後獲得結果
  3. 給相減結果補0,保證相減結果一直都是4位數
  4. 當相減結果等於6174或0時,中斷while循環,返回執行次數

優化點:
1.minArr = num.toString().split('').sort(); minNum = minArr.join(""),那麼maxNum能夠直接使用minArr.reverse().join('')獲得
2.能夠把if判斷內容放到while上
3.補0可使用 num * 10 的方式,而不是字符串補零函數

相關文章
相關標籤/搜索