Task:
Find next greater number with same set of digits
Given a number n, find a smallest number that has same set of digits as n and is greater than n, if x is the greatest possilbe number with its set of digits, then print “no possilbe”.
input: n = 218765
output: 251678
input: n=1234
output: 1243
input: n=4321
output:"no possilbe"
input: n=534976
output:536479
观察后发现:如果要满足题意条件,需从最右边开始逐个数字遍历,当发现最右边的数字大于遍历到的数字的时候,从该数字往后到数字结束,升序排序,交换两个数字。即可得结果。若无满足条件,则输出no possilbe.
例如218765,最右边第一个数字是5,当遍历到1时发现1<5。从1往后升序排列剩下的数字,对调两数位置。即可得251678.
package p_1;
import java.util.Arrays;
public class Main {
public static int n = 534976;
public static void main(String args[])
{
int[] a = new int[20];
int[] b= new int [20];
int count = 0;
while(n>0)
{
count ++;
a[count] = n % 10;
n = n/10;
}
int level = 1;
while(level != count)
{
if(a[1] > a[level])
{
break;
}else
{
level ++;
}
}
if(level == count)
{
System.out.println("No Possible");
}else
{
for(int j = 1;j<count+1;j++)
b[j] = a[count+1-j];
level = count+1-level;
Arrays.sort(b,level,count+1);
int k = b[level];
b[level] = b[level+1];
b[level+1] = k;
for(int i = 1;i<count+1;i++)
System.out.print(b[i]);
}
}
}