用 C++ 查詢給定數字的最小子排列


在這個問題中,我們得到一個大數字 N。我們的任務是找到給定數字的最小子排列。

我們用一個例子來理解這個問題,

輸入

N = 4529016

輸出

1024569

解決方案方法

解決這個問題的一個簡單方法是將長整數值儲存到一個字串中。然後我們將對字串進行排序,作為我們的結果。但如果有任何前導零,我們將把它們移到第一個非零值之後。

演示我們解決方案工作原理的程式,

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
string smallestNumPer(string s) {
   int len = s.length();
   sort(s.begin(), s.end());
   int i = 0;
   while (s[i] == '0')
      i++;
   swap(s[0], s[i]);
   return s;
}
int main() {
   string s = "4529016";
   cout<<"The number is "<<s<<endl;
   cout<<"The smallest permutation of the number is "<<smallestNumPer(s);
   return 0;
}

輸出

The number is 4529016
The smallest permutation of the number is 1024569

更新於:2021 年 3 月 16 日

706 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.