1

I don't understand why this is returning zero:

function largestOfThree (num) {
    let stringyNums = num.toString();
    let highest = 0;

    for (let i = 0; i <= stringyNums.length - 3; i++) {
        let chunk = stringyNums.slice(i, i + 3);
        console.log(chunk);
        if (chunk > highest) chunk = highest;
    }
    return highest;
}
console.log(largestOfThree(123456789));

It seems as though chunk is not getting assigned to highest. I want to assign the new chunk to highest as we're looping through the stringyNums, every time it's greater than the existing highest chunk.

The function should return 789, in this case.

4
  • If chunk is a string, what does chunk > highest actually do? Commented Apr 22, 2019 at 19:21
  • Ah - need to use .parseInt(), maybe. Commented Apr 22, 2019 at 19:22
  • 3
    highest = chunk instead of chunk = highest Commented Apr 22, 2019 at 19:23
  • I don't know if that is the issue, but it is a potential thing to be careful with Commented Apr 22, 2019 at 19:23

5 Answers 5

4

You are not setting highest to chunk Change

if (chunk > highest) chunk = highest;

To

if (chunk > highest) highest = chunk ;
Sign up to request clarification or add additional context in comments.

Comments

3

It's because of this line

if (chunk > highest) chunk = highest;

You're assigning chunk to highest instead of assigning highest to the largest chunk. Simply reverse the two variables and you're good to go.

if (chunk > highest) highest = chunk;

Comments

2

For reference you can accomplish this with a more readable form of a one-liner (6-liner?):

const largestOfThree = num =>
  num
  .toString()
  .match(/.{1,3}/g)
  .map(Number)
  .reduce((acc, curr) => (acc > curr ? acc : curr));

console.log(largestOfThree(123456789));

1 Comment

Nice (+1) but one could quibble with this being described as a "one-liner". I count 6.
1

Try this. You are assigning chunk=highest which is wrong

function largestOfThree (num) {

    let stringyNums = num.toString();
    let highest = 0; 
    for (let i = 0; i <= stringyNums.length - 3; i++) {

        let chunk = stringyNums.slice(i, i + 3);
        console.log(chunk);
        if (chunk > highest) highest=chunk; <---the error was here

    }

    return highest;

}

console.log(largestOfThree(123456789));

Comments

1
largestOfThree(num: number): number {
    const stringyNums = num.toString();
    let highest = 0;
    for (let i = 0; i <= stringyNums.length - 3; i++) {
      let chunk = parseInt(stringyNums.slice(i, i + 3));
      if (chunk > highest) highest = chunk;
    }
    return highest;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.