Java 如果输入的数字为';那不是一个快乐的人吗?
*嗨,这是我对这个挑战的回答: 写一个算法来确定数字n是否“快乐” 快乐数是由以下过程定义的数字:从任何正整数开始,用其数字的平方和替换该数字,然后重复该过程,直到该数字等于1(它将保持不变),或者在不包括1的循环中无限循环。这个过程以1结尾的数字是快乐数字 我的代码可以工作,并且只有当数字是一个快乐的数字时才输出一个真值*Java 如果输入的数字为';那不是一个快乐的人吗?,java,math,primes,happy,Java,Math,Primes,Happy,*嗨,这是我对这个挑战的回答: 写一个算法来确定数字n是否“快乐” 快乐数是由以下过程定义的数字:从任何正整数开始,用其数字的平方和替换该数字,然后重复该过程,直到该数字等于1(它将保持不变),或者在不包括1的循环中无限循环。这个过程以1结尾的数字是快乐数字 我的代码可以工作,并且只有当数字是一个快乐的数字时才输出一个真值* public class Main { public static void main(String[] args) {
public class Main {
public static void main(String[] args) {
System.out.println(isHappy(12));
}
public static boolean isHappy(int number) {
while (number != 1 ) {
number = SumOfintegers(number); //to keep looping until It find sum=1
}
return true ;
}
public static int SumOfintegers(int number){
int sum =0;
int news = 0;
while (number > 0) {
int num = number % 10;
number /= 10;
news = num * num;
sum = sum + news;
}
return sum;
}
}
所以我曾经解决过这个“快乐数字”问题,这是我的代码,使用递归进行解释:
public static void main(String[] args) {
System.out.println(nextHappyNum(0));
}
//method to find next happy number
static int nextHappyNum(int num){
int x =num+1;
if(isHappy(x) == true){ //base case where the next number is happy number
return x;
} else{
return nextHappyNum(num+1); //recursively call the method to check
}
}
//method to check if number is happy or not
static boolean isHappy(int num){
while(num != 1 && num != 4){
num = calculateHappy(num); //this loop will call the checkHappy() method until it reach 1 or 4
}
if(num == 1){ //if result is 1 -> happy number
return true;
} else if(num == 4 ){ //final result is 4 -> not happy number
return false;
} else{
return false;
}
}
//method to calculate the sum of number digits
static int calculateHappy(int num){
int sum = 0;
int rem = 0;
//create while loop to calculate the digit number, remainder of modulus 10 is the second digit
//first digit is = the number/10 and the remainder of that int
while(num != 0){
rem = num%10; //calculating the remainder
sum += (rem*rem); //calculate the square root of remainder and add it to the sum
num = num/10; //divide the number by 10 - due to this data type is int, so the first digit will be taken
}
return sum;
}
请更清楚地解释你的问题。另外,这里不是讨论编码挑战的地方:)请看一下ProjectEulerProblem92以获取帮助。有许多网站就这些问题提供建议。