Square Every Digit in Java

The challenge

You need to square every digit of a number and concatenate them.

For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.

Note: The function accepts an integer and returns an integer.

The solution in Java code

Option 1:

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```public class SquareDigit {

public int squareDigits(int n) {
String result = "";

while (n != 0) {
int digit = n % 10 ;
result = digit*digit + result ;
n /= 10 ;
}

return Integer.parseInt(result) ;
}

}
```Code language: Java (java)```

Option 2:

``````import java.util.stream.Collectors;

public class SquareDigit {

public int squareDigits(int n) {
return Integer.parseInt(String.valueOf(n)
.chars()
.map(i -> Integer.parseInt(String.valueOf((char) i)))
.map(i -> i * i)
.mapToObj(String::valueOf)
.collect(Collectors.joining("")));
}

}
```Code language: Java (java)```

Option 3:

``````public class SquareDigit {
private static final int BASE = 10;

public int squareDigits(int n) {
if (n < BASE) {
return n * n;
}
int digit = n % BASE;
int squaredDigit = digit * digit;
return squaredDigit + (squaredDigit < BASE ? BASE : BASE * BASE) * squareDigits(n / BASE);
}
}
```Code language: Java (java)```

Test cases to validate our solution

``````import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class SquareDigitTest {
@Test
public void test() {
assertEquals(811181, new SquareDigit().squareDigits(9119));
}

}
```Code language: Java (java)```
Tags:
Subscribe
Notify of