Given an array of ints, return true if the sum of all the 2’s in the array is exactly 8.





Following are the test cases

Test cases Result Status
sum28({10,20,30,40,50,60,2}) false OK
sum28({2,10,7,2,2,2}) true OK
sum28({5,6,1,2,2,2}) false OK

Java solution


package test;

public class Program19 {
	public static void main(String[] args) {
		int a[] = {10,20,30,40,50,60,2};
		int b[] = {2,10,7,2,2,2};
		int c[] = {5,6,1,2,2,2};
		Program19.sum28(a);
		Program19.sum28(b);
		Program19.sum28(c);
	}
	public static boolean sum28(int[] nums) {
		int sum = 0;
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] == 2) {
				sum += 2;
			}
		}
		if (sum == 8) {
			return true;
		}
		return false;
	}

}

Javascript solution


const sum28 = (nums) => {
    let sum = 0;
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] === 2) {
            sum += 2;
        }
    }
    if (sum === 8) {
        return true;
    }
    return false;
}

console.log(sum28([10,20,30,40,50,60,2])); //false
console.log(sum28([2,10,7,2,2,2])); //true
console.log(sum28([5,6,1,2,2,2])); //false




About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *