一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直 到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19 输出: true 解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
this.print(); } private void print() { System.out.println("1.***"); } }
class Student extends Person { public void print() { System.out.println("2.###"); } } public class Test{ public static void main(String[] args) { new Student().fun(); } }
1^2 + 0^2 + 0^2 = 1
package jing.able;
import java.util.HashSet;
import java.util.Set;
/**
* @author: panjing
* @describe: 快乐数
* @date: 2019/4/25
* @time: 20:22
*/
public class HappyNumber {
public static boolean isHappyNumber(int num){
if (num <= 0){
return false;
}
int n = num;
//1.%
//2.int->string->char[]->char->string->int
Set<Integer> numbers = new HashSet<>();
while (n != 1) {
int sum = 0;
char[] chars = String.valueOf(n).toCharArray();
for (int i = 0; i < chars.length; i++) {
int bitDig = Integer.parseInt(new String(chars, i, 1));
sum += (bitDig * bitDig);
}
n = sum;
if (numbers.contains(n)) {
return false;
} else {
numbers.add(n);
}
}
return true;
}
public static boolean isHappyNumber2(int num) {
if (num <= 0) {
return false;
}
//1000
int counter = 0;
int n = num;
while (n != 1) {
int sum = 0;
char[] chars = String.valueOf(n).toCharArray();
for (int i = 0; i < chars.length; i++) {
int bitDig = Integer.parseInt(new String(chars, i, 1));
sum += (bitDig * bitDig);
}
n = sum;
counter++;
if (counter > 1000) {
return false;
}
}
return true;
}
}