sum67([1, 2, 2]) → 5
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4
Answer 1:
public int sum67(int[] nums) {
int sum = 0;
boolean stop = false;
for(int i=0;i<nums.length;i++){
if(nums[i]==6) stop=true;
if(!stop)sum += nums[i];
if(nums[i]==7) stop=false;
}
return sum;
}
Answer 2:
public int sum67(int[] nums) {
int sum = 0;
boolean stop = false;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 6)
stop = true;
if (stop == false)
sum += nums[i];
if (nums[i] == 7 && stop == true)
stop = false;
}
return sum;
}
Reference
http://www.javaproblems.com/2013/11/java-array-2-sum67-codingbat-solution.html
No comments :
Post a Comment