Skip to content

Instantly share code, notes, and snippets.

@Maslor
Created August 6, 2015 20:58
Show Gist options
  • Save Maslor/db6b385b9dd5535f1761 to your computer and use it in GitHub Desktop.
Save Maslor/db6b385b9dd5535f1761 to your computer and use it in GitHub Desktop.
class which method receives an Integer and returns an Integer that results of the square of each of the input Integer's digits. i.e. Input: 9119 Output: 811181
import java.util.LinkedList;
import java.lang.Math;
public class SquareDigit {
LinkedList<Integer> stack = new LinkedList<Integer>(); //stack where I'll push each digit for easy ordered extraction
String str = "";
/**
* this method receives a number and returns a number which digits are the input number's digits square.
* Ex: 9119 becomes 811181
* @param int
* @return int
*/
public int squareDigits(int n) {
while (n > 0) {
stack.push(n % 10); //pushes remainder into stack (remainder is the last digit of the number)
n = n / 10;
}
while (!stack.isEmpty()) { //cycle that extracts each of the digits from the stack, in LIFO order
n = (int) stack.pop();
str = str + (n * n); //String str becomes the concatenation of the popped digits, ie our objective
}
return Integer.valueOf(str); //converts the String obtained into an Integer and returns said number
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment