Note- A number is well ordered if all digits are in ascending order ex- 123456789.
Not well ordered number - ex- 2341 (because here 1 is coming after 4 so it is not well ordered.)
Code-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class NumWellOrbered {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int r=0, s=n, j=0;
List<Integer> num = new ArrayList<Integer>();
while(s!=0){
r = s%10;
s = s/10;
num.add(r);
}
for(j=(num.size()-1); j>0; j--){
if(num.get(j)>num.get(j-1)){
System.out.println("Number "+n+" is not well ordered");
break;
}
}
if(j==0){
System.out.println("Number "+n+" is well ordered");
}
}
}
Output 1-
Enter a number: 5436
Number 5436 is not well ordered
Output 2-
Enter a number: 456789
Number 456789 is well ordered
Not well ordered number - ex- 2341 (because here 1 is coming after 4 so it is not well ordered.)
Code-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class NumWellOrbered {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int r=0, s=n, j=0;
List<Integer> num = new ArrayList<Integer>();
while(s!=0){
r = s%10;
s = s/10;
num.add(r);
}
for(j=(num.size()-1); j>0; j--){
if(num.get(j)>num.get(j-1)){
System.out.println("Number "+n+" is not well ordered");
break;
}
}
if(j==0){
System.out.println("Number "+n+" is well ordered");
}
}
}
Output 1-
Enter a number: 5436
Number 5436 is not well ordered
Output 2-
Enter a number: 456789
Number 456789 is well ordered
This comment has been removed by a blog administrator.
ReplyDeletepublic static boolean isWellOrder(int num){
ReplyDeleteint no=num%10;
num=num/10;
while(num>0){
if(!(no>num%10 && (no-num%10) ==1)){
return false;
}
no=num%10;
num=num/10;
}
return true;
}