Sunday, 24 December 2017

An array is called vanilla if all its elements are made up of the same digit. For example {1, 1, 11, 1111, 1111111} is a vanilla array because all its elements use only the digit 1. However, the array {11, 101, 1111, 11111} is not a vanilla array because its elements use the digits 0 and 1. Write a method called isVanilla that returns 1 if its argument is a vanilla array. Otherwise it returns 0.

If you are writing in Java or C#, the function signature is
   int isVanilla(int[ ] a)

If you are writing in C or C++, the function signature is
  int isVanilla(int a[ ], int len) where len is the number of elements in the array a.

Example

if a is
Return
reason
{1}
1
all elements use only digit 1.
{11, 22, 13, 34, 125}
0
Elements used 5 different digits
{9, 999, 99999, -9999}
1
Only digit 9 is used by all elements. Note that negative numbers are okay.
{ }
1
There is no counterexample to the hypothesis that all elements use the same digit.

Solution :
  public int isVanilla(int [] a)
        {
            int rtnVal = 1, rem=0, n = 0, flag = 0;
            if (a.Length > 0)
                flag = a[0] % 10;
            for(int i=0;i<a.Length;i++)
            {
                if (a[i] < 0)
                    a[i] = -1 * a[i];
                n = a[i];
                while(n!=0)
                {
                    rem = n % 10;
                    n = n / 10;
                    if(rem!=flag)
                    {
                        rtnVal = 0;
                        goto label;
                    }
                }
            }
        label:
            return rtnVal;

        }

0 comments:

Post a Comment

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