EDIT : I am unable to keep track of the second largest digit in an integer and swap that with the first digit in the integer to make the integer the largest... (For Example if i have my input as 31548
i am unable to swap 3 with 8 as my code swaps 3 with 5 and gives 51348
and again it runs through the rest and then swaps with 8 and gives 81345
which i don't want...) and For sequences of digits with the highest digit already in the leftmost position like if my input is 877115755 the output should ignore the first three digits 877 and consider the smaller fourth digit 1 and swap the next occurence of 7 and output 877715155.
public static void main(String[] args) {
int value = 621007349;
String number = String.valueOf(value);
int[] arr = new int[number.length()];
int length = (int) (Math.log10(value) + 1);
for (int i = 0; i < length; i++) {
System.out.println("Char at " + number.charAt(i));
arr[i] = number.charAt(i) - '0';
}
int var = 0;
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
for (int j = i; j < arr.length-1; j++) {
if (j < arr.length - 1) {
if (arr[j + 1] > temp) {
if (var < arr[j + 1]) {
var = arr[j + 1];
System.out.println("Larg Val " + arr[j+1]);
System.out.println("First no "+arr[i]);
int tmp = arr[j+1];
arr[j+1] = arr[i];
arr[i] = tmp;
}
}
}
}
}
for (int j = 0; j < arr.length; j++) {
System.out.println("Values in arry are " + arr[j]);
}
}
Input is 621007349
and Output should be 921007346
Please help me on where did i go wrong...
EDIT : Add a while loop to for replacing first possible number with the maximum number after that:
I remove the inner loop and change conditions a little(also remove swap from inside the loop to after loop) and now your code works fine:
public static void main (String[] args) throws java.lang.Exception
{
int value = 877115755;
String number = String.valueOf(value);
int[] arr = new int[number.length()];
int length = (int) (Math.log10(value) + 1);
for (int i = 0; i < length; i++) {
arr[i] = number.charAt(i) - '0';
}
int var = arr[0];
int index = 0;
int startIndex = 0;
boolean changed = false;
while(startIndex<arr.length-1){
var = arr[startIndex];
for (int i = startIndex+1; i < arr.length; i++) {
int temp = arr[i];
if (temp > var) {
var = temp;
index = i;
changed = true;
System.out.println("Larg Val "+arr[i]);
}
}
if(changed)
break;
startIndex++;
}
//this is the swap part
int tmp = arr[index];
arr[index] = arr[startIndex];
arr[startIndex] = tmp;
for (int j = 0; j < arr.length; j++) {
System.out.println("Values in arry are " + arr[j]);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments