We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Warmup
- Simple Array Sum
- Discussions
Simple Array Sum
Simple Array Sum
+ 0 comments How can I get this code on my site? Will it work for wordpress site?
+ 0 comments answer in C#
int sum =0; for (int i = 0; i < ar.LongCount(); i++){ sum = sum + ar[i]; } return sum;
+ 0 comments int sum=0; for (int i=0;i<(ar.Count);i++) { sum+=ar[i]; } return sum;
+ 0 comments public static int simpleArraySum(List<int> ar) { int sum=0; foreach (int number in ar) { sum += number; } return sum; }
+ 0 comments This is my Java solutions, feel free to ask me any questions.
Solution 1:
public static int simpleArraySum(List<Integer> numbers) { int sum = 0; //Iterate through all numbers to calculate sum for(int number : numbers) { sum += number; } return sum; }
An equivalent of the first solution
public static int simpleArraySum(List<Integer> numbers) { // Caculate sum using reduce return numbers.stream() .reduce(Integer::sum) .get(); }
Solution 2:
public static int simpleArraySum(List<Integer> numbers) { // Base case: checking if the current list is empty // return 0 if(numbers.isEmpty()) return 0; // Get the last element of the list int currentNumber = numbers.get(numbers.size() - 1); // Remove the current number from the list numbers.remove(numbers.size() - 1); // Recursive call: sum the current number and // the rest elements. return currentNumber + simpleArraySum(numbers); }
Load more conversations
Sort 3231 Discussions, By:
Please Login in order to post a comment