Make it 1 (with.Java)
In this article, we’ve learned how to make 1.
We’ll be solving coding test problems, reflecting on the problems we solved, and learning about other ways to solve them.
Let’s start with the problem.
Problem
Given an integer, if it’s an even number, divide it in half; if it’s an odd number, subtract 1, divide it in half, and end up with 1. For example, if you have 10, you can divide by 1 using the following process
10 / 2 = 5
(5 - 1) / 2 = 4
4 / 2 = 2
2 / 2 = 1
As shown above, it took four division operations to get to 1.
Given a list num_list of integers, complete the solution function to return the number of division operations required to make all elements of num_list equal to 1.
Example input and output
num_list | result |
---|---|
[12, 4, 15, 1, 14] | 11 |
My solution to the problem
class Solution {
public int solution(int[] num_list) {
int answer = 0;
for(int i = 0; i < num_list.length; i++){
while(num_list[i] != 1){
if(num_list[i] % 2 == 0){
num_list[i] = num_list[i] / 2;
} else{
num_list[i] = (num_list[i] - 1) / 2;
}
answer++;
}
}
return answer;
}
}
solution description
int answer = 0;: Initialize the variable answer to store the result. The initial value is 0.
for(int i = 0; i < num_list.length; i++) : Iterate over the input array num_list, examining each element.
while(num_list[i] != 1) : If the current element is not 1, perform the following action.
if(num_list[i] % 2 == 0) : If the current element is an even number:
Divide the current element by 2.
else : If the current element is odd:
Subtracts 1 from the current element and divides by 2.
answer++;: increments answer by 1 after each operation. This serves to count the number of operations required.
return answer;: Returns answer, which is the sum of the number of operations on each element.