zoukankan      html  css  js  c++  java
  • 30-Day Leetcoding Challenge Day2

    本题涉及判断是否有loop

    两种思路:1.用set存储路径 2.快慢指针法

    JAVA:set()集合法

    class Solution {
        public boolean isHappy(int n) {
            Set<Integer> process = new HashSet<>();
            while(process.add(n)){
                int square = 0;
                while(n != 0){
                    square += (n % 10)*(n % 10);
                    n /= 10;
                }
                if(square == 1)
                    return true;
                else
                    n = square;
            }
            return false;
        }
    }

    JAVA:快慢指针法

    class Solution {
        public boolean isHappy(int n) {
            int slow = n;
            int fast = square(n);
            while(fast != 1){
                slow = square(slow);
                fast = square(fast);
                fast = square(fast);
                if(slow == fast)
                    return false;
            }
            return true;
        }
        public int square(int n){
            int res = 0;
            while(n != 0){
                res += (n%10)*(n%10);
                n /= 10;
            }
            return res;
        }
    }

    python3:set()集合法

    class Solution:
        def isHappy(self, n: int) -> bool:
            process = set()
            while n != 1:
                n = sum([int(x)**2 for x in str(n)])
                if n in process:
                    return False
                else:
                    process.add(n)
            return True

    python3:快慢指针法

    class Solution:
        def isHappy(self, n: int) -> bool:
            slow = n
            fast = self.square(n)
            while fast != 1:
                slow = self.square(slow)
                fast = self.square(fast)
                fast = self.square(fast)
                if slow == fast:
                    return False
            return True
        def square(self, n):
            res = 0
            while n:
                res += (n % 10)**2
                n //= 10
            return res
  • 相关阅读:
    url向视图函数传递参数
    创建django项目
    进度百分比
    【转藏】Makefile学习
    IT人的自我导向型学习:学习的4个层次
    SZ第二次找工作--笔试汇总
    正则表达式 (re包)——python(快餐)
    Python-快速学习
    Vim的使用
    Vim Python
  • 原文地址:https://www.cnblogs.com/yawenw/p/12623969.html
Copyright © 2011-2022 走看看