#K50267. Next Bigger Number

    ID: 28827 Type: Default 1000ms 256MiB

Next Bigger Number

Next Bigger Number

Given a positive integer \(n\), rearrange its digits to form the next greater number. In other words, find the smallest number that is greater than \(n\) using exactly the same digits. If no such number exists, output -1.

Example:

  • Input: 12, Output: 21
  • Input: 513, Output: 531
  • Input: 2017, Output: 2071
  • Input: 111, Output: -1
  • Input: 531, Output: -1

The solution involves finding a pivot digit (using a right-to-left scan) where the next digit is larger, swapping it with the smallest digit on its right that is larger than it, and then sorting (or reversing) the remaining digits to form the minimum possible number.

inputFormat

The input consists of a single positive integer \(n\) provided via standard input (stdin).

outputFormat

Output the next bigger number that can be formed by rearranging the digits of \(n\) to standard output (stdout). If no such number exists, output -1.

## sample
12
21