Reputation: 574
I wrote the following code for finding the last zero index in an array:
public class Stack {
public static void main(String[] args){
int[] a=new int[5];
a[0]=1;
a[1]=0;
a[2]=90;
a[3]=0;
a[4]=4;
findLast(a);
}
public static int findLast(int[] x){
for(int i=0;i<x.length;i++){
if(x[i]==0){
System.out.println(i);
}
}
return 0;
}
}
The output is as follows:
1
3
What I really want is the index 3.
Upvotes: 1
Views: 784
Reputation: 1696
Start from the END of the array and decrement through. Should we never find a zero, this returns -1, which is always outside of the index. This is interpreted by you
public class Stack {
public static void main(String[] args){
int[] a=new int[5];
a[0]=1;
a[1]=0;
a[2]=90;
a[3]=0;
a[4]=4;
findLast(a);
}
public static int findLast(int[] x){
for(int i=x.length-1;i>=0;i--){
if(x[i]==0){
return i;
}
}
return -1;
}
}
Upvotes: 0
Reputation: 574
public static int lastZero(int[] x){
int temp=0;
for(int i=0;i<x.length;i++){
if(x[i]==0){
temp=i;
}
}
System.out.println(temp);
return 0;
}
This would give the desired output.
Upvotes: 0
Reputation: 1102
public class Stack {
public static void main(String[] args){
int[] a=new int[5];
a[0]=1;
a[1]=0;
a[2]=90;
a[3]=0;
a[4]=4;
findLast(a);
}
public static void findLast(int[] x){
for(int i=x.length()-1;i>0;i++){
if(x[i]==0){
System.out.println(i);
break;
}
}
}
}
Upvotes: 2
Reputation: 6121
If your constraint is to traverse the array from the start, Store the index as and when you see 0
into a variable and as you complete the loop just print the variable
int lastindex;
for(int i=0;i<x.length;i++){
if(x[i]==0){
lastindex=i;
}
System.out.println(lastindex);
Upvotes: 0
Reputation: 7487
Just reverse the loop going from x.length-1
to 0
and return the index on first match:
public static int findLast(int[] x) {
for (int i=x.length-1; i>=0; i--) {
if (x[i] == 0) {
// match found, return index
return i;
}
}
// no match found, return invalid index
return -1;
}
Upvotes: 3
Reputation: 726599
i=x.length-1
)i
rather than incrementing (i.e. use i--
)break
after println
).Upvotes: 6