Division of two numbers (with.Java)
This is a post about the ādivision of two numbersā problem.
Weāre going to solve a coding test problem, reflect on the problem we solved, and learn about other ways to solve it.
Letās start with the problem.
Problem
Given the numbers num1 and num2 as parameters, complete the soltuion function so that it returns the integer part of num1 divided by num2 multiplied by 1,000.
Example input and output
num1 | num2 | result |
---|---|---|
7 | 3 | 2333 |
3 | 2 | 1500 |
1 | 6 | 62 |
My solution to the ### problem
class Solution {
public int solution(int num1, int num2) {
int answer = 0;
double result = ((double)num1 / num2) * 1000;
answer = (int) result;
return answer;
}
}
Solution
int answer = 0;: Initialize the variable answer to store the resulting value.
(double)num1 / num2: We first cast num1 to a double, then divide by num2 to calculate the ratio of the two numbers. The reason for doing this is to get the result of the division as a real number.
- 1000: Multiplies the calculated ratio by 1000 to scale the percentage to a thousand times.
(int) result: Cast the calculated result to an integer and store it in answer.
return answer;: Returns the calculated result.