Tuesday, January 24, 2017

Leetcode/各大家 -- 202.258. Happy Number (Math+HashSet), Add Digits(Math)

202. Happy Number (Math + HashSet)
easy
https://leetcode.com/problems/happy-number/
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
Ex: 4, 145 are not happy number
思路: any number after calculation, store it in set. Once encounter any of previous numbers, return false. If n finally goes to 1, return true.

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

258. Add Digits(Math)
easy
https://leetcode.com/problems/add-digits/
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?

public class Solution {
    public int addDigits(int num) {
        while(num >= 10){
            num = helper(num);
        }
        return num;
    }
    public int helper(int num){
        int tmp = 0;
        while(num > 0){
            tmp += num%10;
            num /= 10;
        }
        return tmp;
    }
}
Follow up O(1)
public int addDigits(int num) {
    return 1 + (num - 1) % 9;
}

No comments:

Post a Comment