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
  • 相关阅读:
    初识Comet技术
    巧用JS中的join方法操作字符串
    jquery load ($.load) 事件用法与分析(转)
    jQuery的Ajax操作小结——$.ajax和$.getJSON等用法小结
    lua c api
    __index
    lua 元表
    闭包实现迭代器
    lua 闭包
    select例子
  • 原文地址:https://www.cnblogs.com/yawenw/p/12623969.html
Copyright © 2011-2022 走看看