Biggest and Smallest Number Javascript Error [duplicate] - javascript

This question already has answers here:
Javascript number comparison fails
(2 answers)
Closed 4 years ago.
Challenge:
You are given a string of space-separated numbers and have to return the highest and lowest number.
Problem:
Expected: '542 -214', instead got: '6 -214'
I can't understand why the system thinks 6 is higher than 542. The program works fine when the 6 is removed.
Code:
function highAndLow(numbers){
numbers = numbers.split(" ");
var biggest = numbers[0];
for (i = 0; i < numbers.length; i++) {
if (numbers[i] > biggest) {
biggest = numbers[i];
}
}
var smallest = numbers[0];
for (i = 0; i < numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
return biggest + " " + smallest;
}
console.log(highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"));
JSBin Link

This is because it's comparing the numbers as strings instead of as numbers. You'll want to convert them to numbers using the Number() function to convert them to numbers before you compare them, for example:
biggest = Number(numbers[0]);

Related

JAVASCRIPT nested loops - triangle exercise from user input

I am trying to figure out a triangle excercise where the user inputs a number and the triangle is then created based on said number ex enter 5
This is what I want
**5
6 6
7 7 7
8 8 8 8
9 9 9 9 9
10 10 10 10 10**
Each line the number is increased by 1. I can't get my code to increase by 1.
I keep getting
5
5 5
5 5 5
5 5 5 5
5 5 5 5 5
Anyone have any suggestions? Thanks
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= 6; i++) {
//loop 2
for (y = 0; y < i; y++) {
document.write(num);
}
document.write(num = num +1; "<br>");
}
<p id="num"> </p>
You just have to use the entered number as the loop upper limit:
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= num; i++) {
//loop 2
for (y = 0; y < i; y++) {
document.write(num);
}
document.write("<br>");
}
This syntax is entirely invalid:
document.write(num = num +1; "<br>");
You're somehow confusing calling a function with defining a for loop. Those are two entirely different things.
Don't randomly try to munge together separate operations. Put each operation on its own line of code. The two operations you want to perform are:
Add 1 to num
Output a <br> element
These are separate operations. So separate them:
num = num +1;
document.write("<br>");
You don't seem to be placing the incrementation of your num before writing it to the document. See the code below check the line between loops.
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (let i = 1; i <= 6; i++) {
//loop 2
num++;
for (let y = 0; y < i; y++) {
document.write(num);
}
document.write("<br>");
}
<p id="num"> </p>;

Trying to solve Sum of Digits / Digital Root with JS but having issue, please can any one explain it [duplicate]

This question already has answers here:
Number with leading zeroes gets changed in JavaScript
(4 answers)
Why JavaScript treats a number as octal if it has a leading zero
(3 answers)
Closed 1 year ago.
solving Sum of Digits / Digital Root and facing problem in this case where input is 010 the output comes 8.
please can anyone explain?
function fun(n) {
let numString = n.toString().split("");
let sum = 0;
for (let i = 0; i < numString.length; i++) {
sum += parseInt(numString[i]);
}
console.log(sum);
if (sum >= 10) {
return fun(sum);
}
console.log(numString);
return sum;
}
console.log(fun(010)); // input- 010 and output- 8
Why the output is 8 but it should be 1.

How to use a for loop to find the greatest number in a string

It should be really simple, but the code I wrote isn't seeming to work no matter how I tweak it
I tried splitting the string into an array and using a for loop to loop through and compare all the numbers but I keep on getting the wrong answer
function highAndLow(numbers){
// ...
numbers=numbers.split(" ");
let lowNum=numbers[0];
let highNum=numbers[0];
console.log(numbers)
for (var i = 1; i < numbers.length; i++) {
if (numbers[i]>highNum){
highNum=numbers[i]
}
else if(numbers[i]<lowNum){
lowNum=numbers[i]
}
}
console.log(highNum)
return highNum+" "+lowNum
}
highNum keeps returning 6 when it should return 542, and lowNum is acting weird too...
As others have mentioned, your immediate issue is strings aren't compared the same as numbers, so you must convert the (string) numbers to actual numbers. Beyond that, here is some shorter code for you.
// String of space delimited numbers
var string = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6";
// Split into an array
var nums = string.split(' ');
// Use built-in Math method which with some nifty ES6 syntax
// Note that Math.max/min automatically convert string args to number
var highNum = Math.max(...nums);
var lowNum = Math.min(...nums);
Maybe you try these.
function highAndLow(numbers){
numbers=numbers.split(" ");
let lowNum =+ numbers[0];
let highNum =+ numbers[0];
console.log(numbers);
for (var i = 1; i < numbers.length; i++) {
let num =+ numbers[i];
if (num > highNum){
highNum = num
} else if(num < lowNum) {
lowNum = num
}
}
console.log(highNum)
return highNum + " " + lowNum
}
You need to parse string into numbers before using comparison, else it will be matches lexicographically as string not as number
console.log("22" > "3")
console.log( "22" > 3) // implicit conversion to number
console.log(+"22" > +"3") // explicitly converted to number
string comparision
You can sort() the array and return smallest and largest number. slice() prevents the array itself from being sorted.
var numbers = '4 5 29 54 4 0 -214 542 -64 1 -3 6 -6';
function highAndLow(numbers){
numbers = numbers.split(" ");
let sorted = numbers.slice().sort(function(a, b) {
return a - b;
});
let smallest = sorted[0]
let largest = sorted[sorted.length - 1];
return smallest + "," + largest
}
//call the function
console.log(highAndLow(numbers))

Project Euler 8. Largest product in a series

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
"use strict"
var data = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450"
function largestMulitplication(ValueOfSequence) {
var Numbers, g = 1, ValueOfSequence, arr = [];
Numbers = data.split('');
for (var i = 0; i <= data.length; i++) {
if (i == ValueOfSequence) {
arr.push(g)
ValueOfSequence += 4
g = 1
}
g *= data[i];
}
return Math.max.apply(Math, arr);
}
alert(largestMulitplication(3));
When ValueOfSequence has value 3 and ValueOfSequence += 4 I get 5832 and that's correct. But if I change ValueOfSequence for 29 and ValueOfSequence += 30 I get incorrect answer. Anybody knows why?

The sum of the digits of a number without arrays [duplicate]

This question already has answers here:
Sum all the digits of a number Javascript
(8 answers)
Closed 6 years ago.
given var num = 123456 how can I find the sum of its digits (which is 21 in this case) without using arrays?
var num = 123456, sum = 0;
while ( num > 0 ) { sum += (num % 10)|0; num /= 10; }
document.write(sum);
Hope this helps.!
console.log(sumofdigits(123456));
function sumofdigits(number) {
var sum = 0;
while (number > 0) {
sum += number % 10;
number = Math.floor(number / 10);
}
return sum;
}
Added console.log() as suggested by #nnnnnn

Categories