用 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP