Given an integer array nums, return the sum of the 1st and last element of the array.
Input: nums = [2, 3, 4, 5, 6]
Output: 8
Explanation: 1st element = 2, last element = 6, sum = 2 + 6 = 8.
Input: nums = [2]
Output: 4
Explanation: 1st element = last element = 2, sum = 2 + 2 = 4.
Input: nums = [-1, 2, 4, 1]
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to return the sum of
the 1st and last element of the array */
int sumOfFirstAndLast(vector<int>& nums) {
// Check if the array is empty
if (nums.empty()) {
return 0; // Return 0
}
// Get the first element
int first = nums[0];
// Get the last element
int last = nums[nums.size() - 1];
// Return sum of the first and last elements
return first + last;
}
};
int main() {
vector<int> nums = {2, 3, 4, 5, 6};
// Creating an instance of Solution class
Solution sol;
/* Function call to return the sum of
the 1st and last element of the array */
int ans = sol.sumOfFirstAndLast(nums);
cout << "Sum of first and last element: " << ans;
return 0;
}
class Solution {
/* Function to return the sum of
the 1st and last element of the array */
public int sumOfFirstAndLast(int[] nums) {
// Check if the array is empty
if (nums.length == 0) {
return 0; // Return 0
}
// Get the first element
int first = nums[0];
// Get the last element
int last = nums[nums.length - 1];
// Return sum of the first and last elements
return first + last;
}
public static void main(String[] args) {
int[] nums = {2, 3, 4, 5, 6};
// Creating an instance of Solution class
Solution sol = new Solution();
/* Function call to return the sum of
the 1st and last element of the array */
int ans = sol.sumOfFirstAndLast(nums);
System.out.println("Sum of first and last element: " + ans);
}
}
class Solution:
# Function to return the sum of
# the 1st and last element of the array
def sumOfFirstAndLast(self, nums):
# Check if the array is empty
if not nums:
return 0 # Return 0
# Get the first element
first = nums[0]
# Get the last element
last = nums[-1]
# Return sum of the first and last elements
return first + last
# Creating an instance of Solution class
sol = Solution()
nums = [2, 3, 4, 5, 6]
# Function call to return the sum of
# the 1st and last element of the array
ans = sol.sumOfFirstAndLast(nums)
print("Sum of first and last element:", ans)
class Solution {
/* Function to return the sum of
the 1st and last element of the array */
sumOfFirstAndLast(nums) {
// Check if the array is empty
if (nums.length === 0) {
return 0; // Return 0
}
// Get the first element
let first = nums[0];
// Get the last element
let last = nums[nums.length - 1];
// Return sum of the first and last elements
return first + last;
}
}
// Creating an instance of Solution class
const sol = new Solution();
const nums = [2, 3, 4, 5, 6];
/* Function call to return the sum of
the 1st and last element of the array */
const ans = sol.sumOfFirstAndLast(nums);
console.log("Sum of first and last element:", ans);