Next Bigger Number with Same Digits
Given a positive integer, find the smallest number greater than it that can be formed using exactly the same digits.
If the digits cannot form a greater number, return the original number. Every occurrence of a digit must be used exactly once.
Method Signature
long nextBiggerNumber(long number)
- Returns the smallest number greater than
number that uses exactly the same digits.
- Returns
number itself when no greater arrangement exists.
Constraints
1 ≤ number ≤ 999,999,999,999,999,999
number contains between 1 and 18 digits.
- The solution should not generate every possible arrangement of the digits.
Examples
Example 1
nextBiggerNumber(number = 1,243)
Output: 1,324
The next greater arrangement of the same digits is 1,324.
Example 2
nextBiggerNumber(number = 764)
Output: 764
The digits are already arranged in their greatest possible order.
Example 3
nextBiggerNumber(number = 144)
Output: 414
The repeated digit is preserved, and 414 is the smallest greater arrangement.
Example 4
nextBiggerNumber(number = 230,241)
Output: 230,412
230,412 is the immediate greater number using the same digits.
Example 5
nextBiggerNumber(number = 8)
Output: 8
A single digit cannot be rearranged to form a greater number.