【leetcode】Happy Number(easy)

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

思路:

这题目挺有意思的,肯定不能真的通过无限循环来判断。我观察了一下,估计不happy的数字,运算一圈后会出现前面已经出现过的数字,即在一组数字里绕圈圈。故记录一下出现过的数字,判断是否重复。

如果重复了就不happy,得到1了就happy。

bool isHappy(int n) {
        unordered_set<int> record;
        while(1)
        {
            int sum = 0;
            while(n > 0)
            {
                sum += (n % 10) * (n % 10);
                n /= 10;
            }
            if(sum == 1)
                return true;

            if(record.find(sum) == record.end()) //当前数字没有出现过
            {
                record.insert(sum);
                n = sum;
            }
            else
                return false;

        }
    }

还有用O(1)空间的,就像链表找有没有圈一样,用快慢指针的思路。

public class Solution {
    public boolean isHappy(int n) {
        int x = n;
        int y = n;
        while(x>1){
            x = cal(x) ;
            if(x==1) return true ;
            y = cal(cal(y));
            if(y==1) return true ;

            if(x==y) return false;
        }
        return true ;
    }
    public int cal(int n){
        int x = n;
        int s = 0;
        while(x>0){
            s = s+(x%10)*(x%10);
            x = x/10;
        }
        return s ;
    }
}

还有用数学的,所有不happy的数字,都会得到4.(??why)

bool isHappy(int n) {
    if (n <= 0) return false;

    int magic = 4;
    while (1) {
        if (n == 1) return true;
        if (n == magic) return false;
        int t = 0;
        while (n) {
            t += (n % 10) * (n % 10);
            n /= 10;
        }
        n = t;
    }
}
时间: 2024-10-12 17:09:30

【leetcode】Happy Number(easy)的相关文章

【leetcode】Count Primes(easy)

Count the number of prime numbers less than a non-negative number, n 思路:数质数的个数 开始写了个蛮力的,存储已有质数,判断新数字是否可以整除已有质数.然后妥妥的超时了(⊙v⊙). 看提示,发现有个Eratosthenes算法找质数的,说白了就是给所有的数字一个标记,把质数的整数倍标为false,那么下一个没被标为false的数字就是下一个质数. int countPrimes(int n) { if(n <= 2) retu

【LeetCode】- Valid Number(有效数字)

[ 问题: ] Validate if a given string is numeric.  判断给定的字符串是否是数值 Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true Note: It is intended for the problem sta

【leetcode】Remove Element (easy)

Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. 思路: s记录下一个判断位置, e记录结束位置,把前面的待排除元素与后面要保留的元素互换. int removeE

【leetcode】Same Tree(easy)

Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 思路:太简单! bool isSameTree(TreeNode *p, TreeNode *q) { if(p == NULL &

【leetcode】Reverse Integer(middle)☆

Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 总结:处理整数溢出的方法 ①用数据类型转换long  或 long long ②在每次循环时先保存下数字变化之前的值,处理后单步恢复看是否相等 (比③好) ③整体恢复,看数字是否相等. 思路:注意30000这样以0结尾的数字,注意越界时返回0. 我检查越界是通过把翻转的数字再翻转回去,看是否相等. int rever

【leetcode】3Sum Closest(middle)

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2

【LeetCode】Counting Bits(338)

1. Description Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example: For num = 5 you should return [0,1,1,2,1,2]. 2. Answ

【leetcode】Word Break (middle)

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true because &

【leetcode】Next Permutation(middle)

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replaceme