Leet Code OJ 202. Happy Number [Difficulty: 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
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
翻譯:
寫一個算法去檢測一個數是否是“快樂”的。
“快樂數”按照如下方法定義:首先它是一個正數,使用它的每位數字的平方的和替換它,直到這個數等于1,或者它會一直循環而不到1。這些能夠到1終止的數就是“快樂數”。
分析:
本方案采用遞歸方式去遍歷每個數字,直到它小于10,并且預先算出每個10以內的數字定義是否是“快樂數”。
代碼:
public class Solution {public boolean isHappy(int n) {if(n>9){int sum=0;int nk=n;while(nk>9){sum+=(nk%10)*(nk%10);nk/=10;}sum+=(nk%10)*(nk%10);return isHappy(sum);}if(n==1||n==7){return true;}else{return false;}} }總結
以上是生活随笔為你收集整理的Leet Code OJ 202. Happy Number [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 70. Cli
- 下一篇: Leet Code OJ 101. Sy