import java.util.*; /** * @author huoyin * @version 1.0 2010-11-22 上午12:47:52 * */ public class SquareDigits { private Set<Integer> results = new HashSet<Integer>(); private int target; private int squareOnDigits(int x) { int sum = 0; int y = 0; do { y = x % 10; sum += y*y; x = x/10; }while(x!=0); return sum; } private boolean result(int x){ boolean found = false; while (true) { int m = squareOnDigits(x); if(m==target) { found = true; break; } else if (results.contains(x)) { break; } results.add(m); x = m; } return found; } public int smallestResult(int n) { target = n; int i = 0; for(i=0;;i++){ if(result(i)) { break; } } return i; } public static void main(String[] args) { SquareDigits sd = new SquareDigits(); System.out.println(sd.smallestResult(0)); System.out.println(sd.smallestResult(1)); System.out.println(sd.smallestResult(19)); System.out.println(sd.smallestResult(85)); System.out.println(sd.smallestResult(112)); } }