A Very Big Sum Hackerrank Solution |Java,Python| Codeityweb

A Very Big Sum Hackerrank Solution in java and python | Codeityweb

Problem Description:

You are asked to calculate and print the sum of the elements in an array, but the elements in the array may be quite huge and it cannot be stored in int value.

In this post we are going to discuss
A Very Big Sum Hackerrank Solution |Java| Codeityweb

A very big sum hackerrank solution in java with code and also in python.

It is not a difficult question but as a point of warmup exercise we are discussing the question here.

Inputs can be like this:

1000000001, 1000000002 ,1000000003, 1000000004, 1000000005

 

A Very Big Sum Hackerrank Solution Java:

static long aVeryBigSum(long[] ar) {
long sum=0;
for(long i:ar)
{
sum+=i;
}
return sum;
}
 

Explanation:

  • The Sum is variable is used to store the values on the sum of the array elements.
  • We run  a loop to traverse the elements in the array and add them to the sum variable .
  • Note that we cannot use int here because the sum will exceed the storing capacity of the int data type which is 2^31 -1.

 

A Very Big Sum Hackerrank Solution Python:

 

def aVeryBigSum(ar):
    sum=0;
    for i in range(len(ar)):
    
    sum+=ar[i]
    
    return sum

 

Explanation:

  • Similar to above one we store the sum of array element in the sum variable just the case is that we don't need to worry about the storing capacity of variable.
  • we traverse through the array and calculate the sum and finally return the sum to the calling function.
 
Output:
 
A Very Big Sum Hackerrank Solution |Python| Codeityweb

 

Related Posts:

 

We also have a github repository where you could find solutions for other topics as well.Click Here


Do explore the site for more solutions and along with explanation😀.

If you are a blogger and want to submit a blog post you can do that by contacting us through the contact from provided in the site .

Thank You for Reading!


Post a Comment

0 Comments