检查给定的数字是否快乐
Check whether given number is happy or not
这是我用来检查给定号码是 Happy number 的代码。我想我正在尝试错误的逻辑。
var num = 5239;
var sum = 0;
while (num > 0) {
sum += Math.pow(num % 10, 2);
num = Math.floor(num / 10);
console.log(num)
}
console.log(sum);
if (num == 0) {
alert("happy number")
} else {
alert("Not happy number")
}
请纠正我以获得正确的结果。
https://jsfiddle.net/g18tsjjx/1/
如果我理解什么是快乐数字,这应该是正确的。
$(document).ready(function() {
var num = 1;
var i = 0;
for (i; i < 10000; i++) {
num = newNumber(num);
}
num == 1 ? alert("it's happy number") : alert("it's not happy number");
});
function newNumber(num) {
var sum = 0;
var temp = 0;
while (num != 0) {
temp = num % 10;
num = (num - temp) / 10;
sum += temp * temp;
}
return sum;
}
恐怕您误读了条件:它应该首先检查最终数字是否为 === 1
。
并且您不应该只进行一次迭代,而是继续进行直到达到 1 或遇到已经解析的数字。我建议使用哈希来跟踪已经存在的 seen
个数字。
只是不做一些免费的功课,递归的一个很好的例子here。
根据维基百科
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 either
equals 1 (where it will stay), or it loops endlessly in a cycle that
does not include 1. Those numbers for which this process ends in 1 are
happy numbers, while those that do not end in 1 are unhappy numbers
(or sad numbers). wikipedia Happy number
我创建了递归函数 isHappy
,我们将向其传递我们的 number,所以
考虑到 Happy Number 定义和 javascript 将抛出 Uncaught RangeError: Maximum call stack size exceeded 当我们将无限循环时,我们将把函数放在 try...catch 块中,所以这里是最终代码
//Our Recursive Function
function isHappy(number){
var output = [],
sNumber = number.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));//converting into number
}
var sum=0;
for(var i=0;i<output.length;i++){
sum+=Math.pow(output[i],2);
}
if(sum!==1){
isHappy(sum);
}
}
try{
isHappy(number);//call the function with given number
alert('happy')
}catch(err){
alert('unhappy')
}
this is code for any number. like number can be 3,4,5,6,7,8,9 digits. code helps you.
<!DOCTYPE html>
<html>
<title> Happy number</title>
<head>
<script>
function fun(){
var input = document.myform.t1.value;
do{
var output = [];
var sNumber = input.toString();
var len = sNumber.length;
var sum = 0;
for (var i = 0; i < len; i++)
{
output.push(+sNumber.charAt(i));
}
var j;
var ret= [];
var outlen = output.length;
for (j = 0; j < outlen; j++)
{
ret.push(output[j] * output[j]);
}
var sum = ret.reduce(getSum);
input = sum;
}while(input >= 9);
if(input == 1)
{
document.getElementById("para1").innerHTML = (" given number is happynumber");
}
else
{
document.getElementById("para1").innerHTML = ("not happy number");
}
}
function getSum(total, num) {
return total + num;}
</script>
</head>
<body>
<center>
<form name="myform" method="post" onsubmit="fun(); return false;">
<table border="1">
<tr>
<th colspan="2"> Happy Number </th>
</tr>
<tr>
<th> input number : </th>
<td> <input type="text" name="t1" id="text1" pattern="[0-9]{2,}" title="only numbers allowed" ></td>
</tr>
<tr>
<td colspan="2"> <center><button onclick="fun()">alert</button></center></td>
</tr>
<tr>
<td colspan="2"> <center> <p id="para1" style="color:red;"> </p> </center></td>
</tr>
</table>
</form>
</center>
</body>
</html>
我今天在求职面试中遇到了令人满意的数字。
这是我想出的解决方案。
即使我使用递归,使用看到的数字集应该可以防止堆栈溢出(以及在某些情况下潜在的无限循环)。
'use strict';
function happyNumber(n, unluckySet = new Set()) {
const digitChars = n.toString().split('');
let sum = 0;
digitChars.forEach( digitChar => {
sum += Math.pow(Number.parseInt(digitChar), 2);
});
if (sum === 1) return true; // lucky!
if (unluckySet.has(sum)) return false; // we're unlucky
unluckySet.add(sum);
return happyNumber(sum, unluckySet);
}
// print all happy numbers in range 0..100
for (let i = 0; i <= 100; ++i) {
if (happyNumber(i)) console.log(`${i} is a happy number`);
}
// this still should not cause a stack overflow
const largeHappyNum = 1234567894;
console.log(largeHappyNum, 'is happy:', happyNumber(largeHappyNum));
根据@Kevin阐述,我创建了一个JS版本:
function isHappy(n) {
const next = (n) => {
let ret = 0;
for (const digit of `${n}`) {
ret += (+digit) ** 2;
}
return ret;
};
while (n !== 1 && n !== 4) n = next(n);
return n === 1;
}
console.log(isHappy(5239));
console.log(isHappy(19));
这是我用来检查给定号码是 Happy number 的代码。我想我正在尝试错误的逻辑。
var num = 5239;
var sum = 0;
while (num > 0) {
sum += Math.pow(num % 10, 2);
num = Math.floor(num / 10);
console.log(num)
}
console.log(sum);
if (num == 0) {
alert("happy number")
} else {
alert("Not happy number")
}
请纠正我以获得正确的结果。
https://jsfiddle.net/g18tsjjx/1/
如果我理解什么是快乐数字,这应该是正确的。
$(document).ready(function() {
var num = 1;
var i = 0;
for (i; i < 10000; i++) {
num = newNumber(num);
}
num == 1 ? alert("it's happy number") : alert("it's not happy number");
});
function newNumber(num) {
var sum = 0;
var temp = 0;
while (num != 0) {
temp = num % 10;
num = (num - temp) / 10;
sum += temp * temp;
}
return sum;
}
恐怕您误读了条件:它应该首先检查最终数字是否为 === 1
。
并且您不应该只进行一次迭代,而是继续进行直到达到 1 或遇到已经解析的数字。我建议使用哈希来跟踪已经存在的 seen
个数字。
只是不做一些免费的功课,递归的一个很好的例子here。
根据维基百科
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 either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). wikipedia Happy number
我创建了递归函数 isHappy
,我们将向其传递我们的 number,所以
考虑到 Happy Number 定义和 javascript 将抛出 Uncaught RangeError: Maximum call stack size exceeded 当我们将无限循环时,我们将把函数放在 try...catch 块中,所以这里是最终代码
//Our Recursive Function
function isHappy(number){
var output = [],
sNumber = number.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));//converting into number
}
var sum=0;
for(var i=0;i<output.length;i++){
sum+=Math.pow(output[i],2);
}
if(sum!==1){
isHappy(sum);
}
}
try{
isHappy(number);//call the function with given number
alert('happy')
}catch(err){
alert('unhappy')
}
this is code for any number. like number can be 3,4,5,6,7,8,9 digits. code helps you.
<!DOCTYPE html>
<html>
<title> Happy number</title>
<head>
<script>
function fun(){
var input = document.myform.t1.value;
do{
var output = [];
var sNumber = input.toString();
var len = sNumber.length;
var sum = 0;
for (var i = 0; i < len; i++)
{
output.push(+sNumber.charAt(i));
}
var j;
var ret= [];
var outlen = output.length;
for (j = 0; j < outlen; j++)
{
ret.push(output[j] * output[j]);
}
var sum = ret.reduce(getSum);
input = sum;
}while(input >= 9);
if(input == 1)
{
document.getElementById("para1").innerHTML = (" given number is happynumber");
}
else
{
document.getElementById("para1").innerHTML = ("not happy number");
}
}
function getSum(total, num) {
return total + num;}
</script>
</head>
<body>
<center>
<form name="myform" method="post" onsubmit="fun(); return false;">
<table border="1">
<tr>
<th colspan="2"> Happy Number </th>
</tr>
<tr>
<th> input number : </th>
<td> <input type="text" name="t1" id="text1" pattern="[0-9]{2,}" title="only numbers allowed" ></td>
</tr>
<tr>
<td colspan="2"> <center><button onclick="fun()">alert</button></center></td>
</tr>
<tr>
<td colspan="2"> <center> <p id="para1" style="color:red;"> </p> </center></td>
</tr>
</table>
</form>
</center>
</body>
</html>
我今天在求职面试中遇到了令人满意的数字。 这是我想出的解决方案。
即使我使用递归,使用看到的数字集应该可以防止堆栈溢出(以及在某些情况下潜在的无限循环)。
'use strict';
function happyNumber(n, unluckySet = new Set()) {
const digitChars = n.toString().split('');
let sum = 0;
digitChars.forEach( digitChar => {
sum += Math.pow(Number.parseInt(digitChar), 2);
});
if (sum === 1) return true; // lucky!
if (unluckySet.has(sum)) return false; // we're unlucky
unluckySet.add(sum);
return happyNumber(sum, unluckySet);
}
// print all happy numbers in range 0..100
for (let i = 0; i <= 100; ++i) {
if (happyNumber(i)) console.log(`${i} is a happy number`);
}
// this still should not cause a stack overflow
const largeHappyNum = 1234567894;
console.log(largeHappyNum, 'is happy:', happyNumber(largeHappyNum));
根据@Kevin阐述,我创建了一个JS版本:
function isHappy(n) {
const next = (n) => {
let ret = 0;
for (const digit of `${n}`) {
ret += (+digit) ** 2;
}
return ret;
};
while (n !== 1 && n !== 4) n = next(n);
return n === 1;
}
console.log(isHappy(5239));
console.log(isHappy(19));