Find the next greater number
Given a number find the smallest number that is greater than n, and has same number of digits as n.
Steps:
Consider 3,2,8,4,1
1. Start from right and find the digit that is smaller than its next digit.
3,2 < 8 >4 >1
2. Swap that digit with its next higher number in the right.
3, 2, 8, 4 , 1 (next higher digit of 2 is 4)
3,4,8,2,1
3. Reverse the digits to the right of that digit (4).
3,4,1,2,8
Code:
import java.util.*;
public class Solution {
static void findNextGreater(int[] a){
int n = a.length;
int position = -1;
for(int i=n-1; i>0; i--){
if(a[i]>a[i-1]){
position = i-1;
break;
}
}
int smallest = position+1;
//here we have to find the next higher number. The number has to be higher than a[position]
//and smaller than other digits, we initialize smallest to a[poisition+1] as it is
// higher than a[poistion]
for(int i=position+2; i<n; i++){
if(a[i]>a[position] && a[i] < a[smallest])
smallest = i;
}
swap(a, position,smallest);
reverse(a, position+1);
}
static void swap(int[] a, int position, int nexthigh){
int temp = a[position];
a[position] = a[nexthigh];
a[nexthigh] = temp;
}
static void reverse(int[] a, int start){
int n = a.length;
for(int i=start, j=n-1; i<j; i++,j--){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public static void main(String[] args) {
int[] a = {3,2,8,4,1} ;
findNextGreater(a);
for(int i=0; i<a.length; i++){
System.out.print(a[i]);
}
}
}
Output:
Input: n = "218765"
Output: "251678"
Input: n = "1234"
Output: "1243"
Input: n = "4321"
Output: "Not Possible"
Input: n = "534976"
Output: "536479"
Steps:
Consider 3,2,8,4,1
1. Start from right and find the digit that is smaller than its next digit.
3,2 < 8 >4 >1
2. Swap that digit with its next higher number in the right.
3, 2, 8, 4 , 1 (next higher digit of 2 is 4)
3,4,8,2,1
3. Reverse the digits to the right of that digit (4).
3,4,1,2,8
Code:
import java.util.*;
public class Solution {
static void findNextGreater(int[] a){
int n = a.length;
int position = -1;
for(int i=n-1; i>0; i--){
if(a[i]>a[i-1]){
position = i-1;
break;
}
}
int smallest = position+1;
//here we have to find the next higher number. The number has to be higher than a[position]
//and smaller than other digits, we initialize smallest to a[poisition+1] as it is
// higher than a[poistion]
for(int i=position+2; i<n; i++){
if(a[i]>a[position] && a[i] < a[smallest])
smallest = i;
}
swap(a, position,smallest);
reverse(a, position+1);
}
static void swap(int[] a, int position, int nexthigh){
int temp = a[position];
a[position] = a[nexthigh];
a[nexthigh] = temp;
}
static void reverse(int[] a, int start){
int n = a.length;
for(int i=start, j=n-1; i<j; i++,j--){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public static void main(String[] args) {
int[] a = {3,2,8,4,1} ;
findNextGreater(a);
for(int i=0; i<a.length; i++){
System.out.print(a[i]);
}
}
}
Output:
34128
Comments
Post a Comment