Sunday, 24 December 2017

Question :
Write a function sumIsPower with signatuare
boolean sumIsPower(int[] arr)                      
which outputs true if the sum of the elements in the input array arr is a power of 2, false otherwise. Recall that the powers of 2 are 1, 2, 4, 8, 16, and so on. In general a number is a power of 2 if and only if it is of the form 2n for some nonnegative integer n. You may assume (without verifying in your code) that all elements in the array are positive integers. If the input array arr is null, the return value should be false.

Examples:  sumIsPower({8,8,8,8}) is true since 8 + 8 + 8 + 8 = 32 = 25.  sumIsPower({8,8,8})  is false, since 8 + 8 +8 = 24, not a power of 2.

Solution :
public static bool sumIsPower(int[] arr)
        {
            int power = 2, sum = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                sum += arr[i];
                power *= 2;
            }
            if (sum == power)
                return true;
            else
                return false;

        }

5 comments:

  1. arr = {16} ---returns false it should be true

    ReplyDelete
  2. public static boolean sumIsPower(int[] arr)
    {
    int sum = 0;
    boolean result = true;
    for (int i = 0; i < arr.length; i++)
    {
    sum += arr[i];
    }
    while(sum !=1) {
    if(sum%2!=0) {
    result = false;
    }
    sum = sum/2;
    }
    return result;

    }

    ReplyDelete

Powered by Blogger.

Followers

Translate

Currency Converter

Exchange Rate

Featured post

Interpolation in angular 5

When we want to communicate from component class to template ,we can use interpolation which use the { { expression }} to render the bound...

Popular Posts

My Facebook Page