Problem:
Given an array of ints, return true if the sum of all the 2's in the array is exactly 8.
sum28({2, 3, 2, 2, 4, 2}) → true
sum28({2, 3, 2, 2, 4, 2, 2}) → false
sum28({1, 2, 3, 4}) → false
Solution:
public boolean sum28(int[] nums) { int sum = 0; boolean is8 = false; for (int i = 0; i < nums.length; i++) { if (nums[i] == 2) sum += 2; } if (sum == 8) is8 = true; return is8; }
public boolean sum28(int[] nums) {
ReplyDeleteint sum = 0;
for (int i : nums) {
if (i==2) sum += 2;
}
return sum==8;
}
public boolean sum28(int[] nums) {
ReplyDeleteint count=0;
for(int i=0; i<nums.length; i++){
if(nums[i]==2){
count++;
}}
if(count==4){
return true;
}
return false;
}
public boolean sum28(int[] nums) {
ReplyDeleteint sum = 0;
for(int i = 0; i < nums.length && sum <= 8; i++) {
if(nums[i] == 2) sum += nums[i];
}
return sum == 8;
}
if we still left some cells in the array and sum is already grater then 8 then stop and return false
public boolean sum28(int[] nums) {
ReplyDeleteint count = 0;
for(int i = 0; i<nums.length; i++) {
if(nums[i]==2) count++;
}
return count == 4;
}
public boolean sum28(int[] nums) {
ReplyDeleteint sum=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==2){
sum+=nums[i];
}
}
return sum==8?true:false;
}
public boolean sum28(int[] nums) {
ReplyDeleteboolean results = false;
int sum = 0;
for(int i = 0; i<nums.length; i++){
if(nums[i] == 2)
sum += nums[i];
}
if(sum == 8)
{
results = true;
}
return results;
}
public boolean sum28(int[] nums) {
ReplyDeleteint sum=0;
boolean counter = false;
for(int i=0;i<nums.length;i++)
if(nums[i]==2)
sum+=nums[i];
if(sum==8)
counter=true;
return counter;
}
public boolean sum28(int[] nums) {
ReplyDeleteint count = 0;
for(int i=0; i < nums.length; i++){
if(nums[i]==2){
count++;
}
}
if(count*2==8){
return true;
}
return false;
}
public boolean sum28(int[] nums) {
ReplyDeleteint sum = Arrays.stream(nums)
.filter(n -> n == 2).sum();
if(sum == 8) return true;
else return false;
}
public boolean sum28(int[] nums) {
ReplyDeleteboolean result = false;
int count2 = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == 2)
count2++;
}
if (count2 == 4){
result = true;
}
return result;
}