用 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