房地产开发公司招聘兰州网站seo优化
1、快乐树
//编写一个算法来判断一个数 n 是不是快乐数。 // // 「快乐数」定义为: // // // 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。 // 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。 // 如果 可以变为 1,那么这个数就是快乐数。 // // // 如果 n 是快乐数就返回 true ;不是,则返回 false 。 // // // // 示例 1: // // //输入:19 //输出:true //解释: //12 + 92 = 82 //82 + 22 = 68 //62 + 82 = 100 //12 + 02 + 02 = 1 // // // 示例 2: // // //输入:n = 2 //输出:false // // // // // 提示: // // // 1 <= n <= 231 - 1 // // Related Topics 哈希表 数学
方法一: 快慢指针
判断一个链表是否有环,如果有,那么快指针和慢指针总会在某一个节点处相遇,如果没有,那么快指针肯定比慢指针先到数字1。可以参见题解:
https://leetcode-cn.com/problems/happy-number/solution/kuai-le-shu-by-leetcode-solution/
public boolean isHappy(int n) {//快慢指针法int fast = n;int slow = n;do{slow = add_Bit(slow);fast = add_Bit(fast);fast = add_Bit(fast);}while (fast != slow);if(fast == 1){return true;}else{return false;}}private int add_Bit(int a){int sum = 0;while(a != 0){sum += (a%10)*(a%10);a /= 10;}return sum;}
方法二:用哈希集合检测循环
public boolean isHappy(int n) {//集合计算法List<Integer> list = new ArrayList<>();while(n != 1 && !list.contains(n)){list.add(n);n = add_Bit(n);}return n==1;}
private int add_Bit(int a){int sum = 0;while(a != 0){sum += (a%10)*(a%10);a /= 10;}return sum;}
2、计算质数
//统计所有小于非负整数 n 的质数的数量。 // // // // 示例 1: // // 输入:n = 10 //输出:4 //解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 // // // 示例 2: // // 输入:n = 0 //输出:0 // // // 示例 3: // // 输入:n = 1 //输出:0 // // // // // 提示: // // // 0 <= n <= 5 * 106 // // Related Topics 哈希表 数学
用埃氏筛,把所有合数给筛出去,具体可以看题解:
https://leetcode-cn.com/problems/count-primes/solution/ji-shu-zhi-shu-by-leetcode-solution/
public int countPrimes(int n) {boolean[] isPrimes = new boolean[n];Arrays.fill(isPrimes, true);for (int i = 2; i*i < n; i++) {if(isPrimes[i]){for (int j = i*i; j < n; j+=i) {isPrimes[j] = false;}}}int count = 0;for (int i = 2; i < n; i++) {if(isPrimes[i]){count++;}}return count;}