public class Test26 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums={1,9,1,9,4};
System.out.println("return value boolean is--->"+arrayFront9(nums));
}
public static boolean arrayFront9(int[] nums) {
int count=0;
for(int num: nums){
if(num==9)
count++;
}
if(count>=4)
return true;
/*if(count<4)
return false;*/
return false;
}
}
public boolean arrayFront9(int[] nums) {
int count=0;
for(int num: nums){
count++ ;
if(num==9 && count <= 4)
return true ;
}
return false;
}
count++ ;
if(num==9 && count <= 4above statement it will make sure it will check till 4th position only not beyond that and also value is 9 right?
The method of http:#a40425004 does work for that, but it may be worth noting that if you have a very long array, it could do a lot more work than it needs to before returning false.
The method of http:#a40425004 does work for that, but it may be worth noting that if you have a very long array, it could do a lot more work than it needs to before returning false.
Is there is a way to improve it? please advise
public boolean arrayFront9(int[] nums) {
for (int count = 0 ; count < nums.length && count < 4 ; count++) {
int num = nums[count];
if(num==9)
return true ;
}
return false;
}
Is there is a way to improve it?You might change
count < nums.length && count < 4
You might change
if(num==9 && count <= 4)
return true ;
to
if(num==9 )
return true ;
if( count==4 )
return false;
count < nums.length && count < =4
You might change
if(num==9 && count <= 4)
return true ;
to
if(num==9 )
return true ;
if( count==4 )
return false;
You might change
if(num==9 && count <= 4)
return true ;
to
if(num==9 )
return true ;
if( count==4 )
return false;
do you mean it should be like below(within foreach loop? Please adviseIn this case, since you do need the count index, and don't always scan all elements of the arraywhich case you are referring http:#a40426848 or http:#a40427058
public boolean arrayFront9(int[] nums) {
int count=0;
for(int num: nums){
count++ ;
if(num==9 )
return true ;
if( count==4 )
return false;
}
return false;
}
what would be the difference. To me both approaches looks same.please advise.
public boolean arrayFront9(int[] nums) {
for (int count = 0 ; count < nums.length && count < 4 ; count++) {
int num = nums[count];
if(num==9)
return true ;
}
return false;
}
public boolean arrayFront9(int[] nums) {
for (int count = 0 ; count < nums.length && count < 4 ; count++) {
int num = nums[count];
if(num==9)
return true ;
}
return false;
}
If you are experiencing a similar issue, please ask a related question
Title | # Comments | Views | Activity |
---|---|---|---|
Adjust the position | 3 | 60 | |
What language/protocol is the Angular Chat? | 2 | 77 | |
xampp tool | 12 | 50 | |
table example | 4 | 29 |
Join the community of 500,000 technology professionals and ask your questions.