About finding multiples of n (with. Java)
In this article, we learned about comparing two numbers (with.Java)
We’re going to go through the Coding Test questions, reflecting on the problems we solved, and learning about other ways to solve them. Let’s start with the problem.
Problem
Given an integer num and n as parameters, complete the solution function so that it returns 1 if num is a multiple of n and 0 if it is not a multiple of n.
Example input and output
num: 98 n: 2 result: 1
In other words, since 98 is a multiple of 2, 1 should be the result.
My solution to the problem
class Solution {
public int solution(int num, int n) {
int answer = 0;
answer = (num % n == 0) ? 1 : 0;
return answer;
}
}
The key was to determine the multiple, so we divided num by n via the % operator and determined that if the remaining value was 0, it was a multiple, so we put a 0 in answer if it wasn’t a 1.