LeetCode编程练习

来源:互联网 发布:淘宝网店开店流程 编辑:程序博客网 时间:2024/06/06 00:09

题目:

   Write an algorithm to determine if a number is "happy".

         A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

         Example: 19 is a happy number

                    12 + 92 = 82

                    82 + 22 = 68

                    62 + 82 = 100

                    12 + 02 + 02 = 1

       定义一种快乐数,就是说对于某一个正整数,如果对其各个位上的数字分别平方,然后再加起来得到一个新的数字,再进行同样的操作,如果最终结果变成了1,则说明是快乐数,如果一直循环但不是1的话,就不是快乐数。数字19就是一个快乐数。


思路:
    解决方案中用到了哈希集HastSet<T>,HastSet<T>相似与List<T>,不过哈希集无排序的功能,是以数学Set集合为基础,可提高集合的运算,无法向里面添加重复的数据。Contains用来判断元素是否存在。在使用的时候要注意HashSet是有缓存的,第一次执行完后会缓存所有的HashSet,以后再调用Contains比较的时候使用缓存的Hashset,因此HashSet最好只用来存储不可变对象,否则Contains方法的返回值是不准确的。最后的返回值恒等于1,是为了将bool值转换为int型,对于不可变类要尽量满足1,避免Set比较时出现问题。
    为确保严谨性,先判断数值是否是一个正数,然后再执行下一步,定义一个HastSet<int>哈希集用来保存中间出现的结果。判断数值不为1并且不能重复出现,若数值是大于0的数,便对数值的各个位平方相加。在对于对数值的运算这方面我的想法与解决方案不同,但是我的想法显然是错误的,输出结果不符。

     解决方案: