Converting a sequence to meet a condition 3 (with.Java)
This is a recap of the “Convert a sequence to match a condition 3” problem.
We’re going to learn by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them.
Let’s start with the problem
Problem
Given an array of integers arr and a natural number k.
If k is odd, multiply every element in arr by k. If k is even, add k to every element in arr.
Complete a solution function that returns arr after these transformations.
Example input and output
arr | k | result |
---|---|---|
[1, 2, 3, 100, 99, 98] | 3 | [3, 6, 9, 300, 297, 294] |
[1, 2, 3, 100, 99, 98] | 2 | [3, 4, 5, 102, 101, 100] |
My solution to the ### problem
class Solution {
public int[] solution(int[] arr, int k) {
if(k % 2 == 0){
for(int i = 0; i < arr.length; i++){
arr[i] += k;
}
}else{
for(int i = 0; i < arr.length; i++){
arr[i] = arr[i] * k;
}
}
} return arr;
}
}
Solution Explanation
if(k % 2 == 0) : if k is an even number:
Add k to each element of the array arr.
else : Otherwise (i.e., if k is odd):
Multiply each element of the array arr by k.
return arr;: Returns the changed array arr.
This code converts the elements of the array differently depending on whether k is odd or not.
If k is even, it adds k to each element; if k is odd, it multiplies each element by k and returns it.