Leet Code OJ 202. Happy Number [Difficulty: Easy]
来源:互联网 发布:软件认定企业查询 编辑:程序博客网 时间:2024/05/01 23:21
题目:
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; } }}
0 0
- Leet Code OJ 202. Happy Number [Difficulty: Easy]
- Leet Code OJ 263. Ugly Number [Difficulty: Easy]
- Leet Code OJ 171. Excel Sheet Column Number [Difficulty: Easy]
- Leet Code OJ 191. Number of 1 Bits [Difficulty: Easy]
- Leet Code OJ 292. Nim Game [Difficulty: Easy]
- Leet Code OJ 242. Valid Anagram [Difficulty: Easy]
- Leet Code OJ 231. Power of Two [Difficulty: Easy]
- Leet Code OJ 258. Add Digits [Difficulty: Easy]
- Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]
- Leet Code OJ 283. Move Zeroes [Difficulty: Easy]
- Leet Code OJ 217. Contains Duplicate [Difficulty: Easy]
- Leet Code OJ 169. Majority Element [Difficulty: Easy]
- Leet Code OJ 100. Same Tree [Difficulty: Easy]
- Leet Code OJ 70. Climbing Stairs [Difficulty: Easy]
- Leet Code OJ 101. Symmetric Tree [Difficulty: Easy]
- Leet Code OJ 112. Path Sum [Difficulty: Easy]
- Leet Code OJ 168. Excel Sheet Column Title [Difficulty: Easy]
- Leet Code OJ 38. Count and Say [Difficulty: Easy]
- java中基本输入输出流的解释
- java.toString() ,(String),String.valueOf的区别
- CF 118A string task
- Linux Mint下的Tomcat安装及配置
- 模态从第三个控制器返回到第一个控制器
- Leet Code OJ 202. Happy Number [Difficulty: Easy]
- 在VMWare安装Xinu
- 傻瓜学算法系列之排序——3.选择排序
- Android 自定义RecyclerView 实现真正的Gallery效果
- java 用嵌套for循环实现九九乘法表各种形状的展现
- UVA 712 S-Trees
- 使用Keychain配置
- 判断是否为回文
- UVA 536 Tree Recovery