-1

The result of this script is not the sum of the squares of the digits of a number, the first function works fine, I guess the problem is in the second

function nToArray(a) {
  var res=[];
  var s =a.toString();
  for(i=0;i<s.length;i++){
    res[i]=s.charAt(i);}
  return res;
}

 //var a ="hola";
 //document.write(a.length);
alert(nToArray(562));
function addSq(b){
  var c=nToArray(b);
  var z=0;
  var i;
  for (i=0;i<=c.length;i++){//here 
    z+=((parseInt(c[i]))^2);}
  return z;
}

alert(addSq(81));

For 81 I get 15, I don't get it.

Kepol
  • 149
  • 1
  • 8

5 Answers5

2

JavaScript doesn't have an exponentiation operator, ^ is a bitwise integer XOR.

You're looking for Math.pow.

z += Math.pow(parseInt(c[i]), 2);

or of course, just use * to multiply:

var value = parseInt(c[i]);
z += value * value;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

Here is a short version - sorry about the missing formatting:

var a=81;
console.log(a.toString().split('').map(function(i) {return Math.pow(i, 2)}).reduce(function(a, b) {return a + b}));
mzedeler
  • 4,177
  • 4
  • 28
  • 41
1

While ^ represents an exponent in some languages, that is not the case in JavaScript.

Change

z+=((parseInt(c[i]))^2);

to

var tmp = parseInt(c[i]);
z+= tmp * tmp;
Eric J.
  • 147,927
  • 63
  • 340
  • 553
1

Hope this helps:

EDIT

function addSq(num){
var numNoStr = parseInt(num, 10);
var z = 0;
while (numNoStr > 0) {
    var digit = numNoStr % 10;
    z += Math.pow(digit, 2);
    numNoStr = parseInt(numNoStr / 10 , 10);
}
return z;
}
alert(addSq(81));
guysigner
  • 2,822
  • 1
  • 19
  • 23
1

You can do this numerically:

function sum_of_squares_of_digits(n) {
  var s = 0;
  while (n) {
    var digit = n % 10;
    s += digit * digit;
    n = (n - digit) / 10;
  }
  return s;
}

Just for fun, try using regexp:

function sum_of_squares_of_digits(n) {
  var s = 0;
  n.toString().replace(/\d/g, d => s += d * d);
  return s;
}