It would be awesome if someone could give me a proper explanation of the code :)
Code is working and I like it, however as I am learning Java, need to understand every bit of it.
Thanks!
Checked StringBuilder()
- seems fine,
However part inside the loop
is not quite clear.
public class SquareDigit {
public int squareDigits(int n) {
StringBuilder builder = new StringBuilder();
while(n > 0) {
int digit = n % 10;
int square = digit * digit;
builder.insert(0, square);
n = Math.floorDiv(n, 10);
}
return Integer.valueOf(builder.toString());
}
}
while(n > 0) {
While the int n
is bigger than 0 do the following.
int digit = n % 10;
A new int digit
is initialized as n MODULO 10. Modulo returns the remainder of the division n / 10. So for example if n is 21, it will return 1.
int square = digit * digit;
builder.insert(0, square);
A new int square
is initialised as the product of digit
times itself. The method insert()
from class StringBuilder
is called with 0 and square
as parameters. 0 is the offset and square
is the char value to be inserted.
n = Math.floorDiv(n, 10);
Math.floorDiv()
returns the largest (closest to positive infinity) integer value that is less than or equal to the algebraic quotient. For example Math.floorDiv(25, 5)
will return 5
.
return Integer.valueOf(builder.toString());
Finally, you return the value you built before. builder.toString()
returns the StringBuilder
object as a String. Integer.valueOf(String str)
is used to return an Integer
object holding the value of the specified String str
.