I am solving this problem on code forces.
It outputs -1
one twice in the same case, which shows that the break
statement isn't taking me outside the loop?
Why is this happening?
public class vanita {
public static void main (String[]args) {
Scanner in = new Scanner(System.in);
int cases = in.nextInt();
for (int i = 0; i < cases; i ) {
boolean test = true;
int arrLength = in.nextInt();
int arr[] = new int[arrLength];
for (int j = 0; j < arrLength; j ) {
arr[j] = in.nextInt();
}
int operations = 0;
int after;
for (int j = arrLength-1; j >= 1 ; j--){
after = arr[j-1];
while (arr[j] <= after) {
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations ;
if (arr[j] == 0 && arr[j-1] == 0) {
//System.out.println("current: " arr[j]);
//System.out.println("after: " arr[j-1]);
//System.out.println("Case " i);
System.out.println("-1");
test = false;
break;
}
}
}
for (int s = 0; s < arrLength; s ) {
//System.out.print(arr[s] " ");
}
//System.out.println(" ");
if (test == true) {
System.out.println(operations);
}
}
}
}
CodePudding user response:
i think it breaks out of the inner while loop, but not the outer for loop. So the inner while loop runs multiple times.
CodePudding user response:
Problems
Normally a break;
will always break out of the most recent loop. If you can't break out of your loop, the the problem is your algorythm or your condition.
Solutions
First, always debug to see if you enter your if statement.
Second, use something else as condition of your while loop. Use a boolean and change it's value to break the while' condition. Ex:
boolean hasFoundDuplicate = false;
while(!hasFoundDuplicate){
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations ;
if(arr[j] == 0 && arr[j-1] == 0){
hasFoundDuplicate = true;
}
}