Contents

For the rest of the implementation methods divided by 9 (with. Java)

   Sep 3, 2023     2 min read

In this article, we learned about For the rest of the implementation methods divided by 9 (with. Java)

We’re going to learn as we go along, solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them. Let’s start with the problem.

Problem

It is known that the remainder of a non-negative integer divided by 9 is equal to the sum of each digit of that integer divided by 9. Use this fact to write a solution function that, given a non-negative integer as a string number, returns the remainder of that integer divided by 9.

Example input and output

number: β€œ78720646226947352489” result: 2

The number is 78720646226947352489 and the sum of the digits is 101. The remainder of 101 divided by 9 is 2, which is actually 78720646226947352489 = 9 Γ— 8746738469660816943 + 2. Therefore, it returns 2.

My solution to the problem

class Solution {
    public int solution(String number) {
        int answer = 0;
        int temp = 0;
        for(int i = 0; i < number.length(); i++){
            temp += (number.charAt(i) - '0');
        }

        answer = temp % 9;
        return answer;
    }
}
Solution

Declare the variable temp to temporarily store an integer value. Iterate over the length of number, and store all the elements of number together in temp. (number.charAt(i) - β€˜0’); For this code, we utilized the charAt() function to convert number, which is a list of integers in one string, to a character type and count them one by one. This function can be used as it is when returning as a String, but when returning as an Integer, it is received as ASCII and must be subtracted by the string β€˜0’ to be recognized as the integer type we intended. If it is returned directly as an integer without subtraction, it will be returned with 48 added during the char to int conversion. This is because β€˜0’ is 48, which is the Ascii code value of 48. If the loop completes correctly, we end up with ANSWER returning the value of temp % 9.