Contents

Division of two numbers (with.Java)

   Dec 13, 2023     1 min read

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

num1num2result
732333
321500
1662

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.