Find next greater number with same set of digits

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]);
		}
		
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值