Topcoder_2_1

来源:互联网 发布:php 常用函数 编辑:程序博客网 时间:2024/04/27 15:25
【问题描述】
    定义一个函数S(x) ,该函数用于计算x的所有数位的平方和。例如,S(3)=3*3=9、S(230)=2*2+3*3+0*0=13
    定义一个集合T(x),它包含非重复的由函数S(x)生成的一系列数字。
    例如,对37应用S函数:
S(37)=3*3+7*7=58.  
S(58)=5*5+8*8=89.
S(89)=145.
S(145)=42.
S(42)=20.
S(20)=4.
S(4)=16.
S(16)=37.
    该序列会重复,因此计算到16为止,得到集合T为T(37)={58,89,145,42,20,4,16,37}。然而,集合T(x)中也许不包含x。
    现在要求给定一个数字n,要求计算一下包括该数字的T(x)集合,需要得到满足以上要求的x的最小值。(n是一个非负整数,取值范围为0至199)
  定义:
类  SquareDigits
方法  public int smallestResult(int n);
  测试用例:
n=1 -> x=1
n=19 -> x=133
n=85 -> x=5
n=112 -> x=2666
  1. import java.util.HashSet;
  2. public class SquareDigits {
  3.     private int calSum(int num) {
  4.         int sum = 0, tmp;
  5.         while (num > 0) {
  6.             tmp = num % 10;
  7.             num = num / 10;
  8.             sum = sum + tmp * tmp;
  9.         }
  10.         return sum;
  11.     }
  12.     public int smallestResult(int n) {
  13.         HashSet<Integer> res = new HashSet<Integer>();
  14.         int index = -1, tmp;
  15.         while (!res.contains(n)) {
  16.             tmp = ++index;
  17.             while (true) {
  18.                 tmp = calSum(tmp);
  19.                 if (res.contains(n))
  20.                     return index;
  21.                 else if (res.contains(tmp))
  22.                     break;
  23.                 else
  24.                     res.add(tmp);
  25.             }
  26.         }
  27.         return index;
  28.     }
  29. }
【算法思想】
    利用一个假设的前提,也就是给定一个x,不停对其进行S的计算,则一定会出现重复的情况,也就是说得到的结果数列将会是循环的。
原创粉丝点击