Leetcode 2562. Find the Array Concatenation Value
Given a 0-indexed integer array nums
, the concatenation value of nums
is initially empty. Initially, the length of nums
is n
.
Perform the following steps until nums
becomes empty:
nums
, move the final element to the concatenation value.nums
, the first being the leftmost element and the second being the rightmost element.nums
and add their concatenation to the concatenation value.The concatenation of two integers means the concatenated form of their string representations. For example, if the left number is 12 and the right number is 34, the concatenation is “1234”.
Return the concatenation value as an integer.
nums
array?nums
always positive integers?#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
long long findTheArrayConcVal(vector<int>& nums) {
if (nums.empty()) return 0;
int left = 0;
int right = nums.size() - 1;
string result = "";
while (left <= right) {
if (left == right) {
result += to_string(nums[left]);
} else {
result += to_string(nums[left]) + to_string(nums[right]);
}
left++;
right--;
}
return stoll(result);
}
};
int main() {
Solution sol;
vector<int> nums = {1, 2, 3, 4, 5};
cout << sol.findTheArrayConcVal(nums) << endl;
return 0;
}
left
at the beginning and right
at the end of the array.left
equals right
), append this single element’s string representation to the result.left
pointer to the right and the right
pointer to the left to process the next pair of elements.stoll()
.This algorithm efficiently concatenates pairs of integers from the array by leveraging string operations and handles edge cases where the array has an odd length naturally.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?