Contents

Integer parts (with.Java)

   Nov 7, 2023     1 min read

This is a post about the ā€œinteger partialsā€ problem.

Weā€™re going to learn about it by solving coding test problems, reflecting on the problems weā€™ve solved, and exploring other ways to solve them.

Letā€™s start with the problem.

Problem

Complete the solution function so that, given a real number flo as a parameter, it returns the integer part of flo.

Example input and output
floresult
1.421
69.3269

My solution to the problem

class Solution {
    public int solution(double flo) {
        int answer = (int) flo;
        return answer;
    }
}
Solution Explained

To convert a float value to an int value, you must use explicit casting.

When converting from a float value to an int value, decimal values are discarded. In Java, we use (int) to perform the cast.

See ######

Casting can cause data loss, so you should be careful. If you want to preserve decimal values, you should use rounding or other methods.