How can i reverse numbers with loop [duplicate] - javascript

This question already has answers here:
Reverse decimal digits in javascript
(14 answers)
Closed 6 years ago.
I trued to use my code that was written in c++ to output reversed number with while loop and i got output of "Infinity"
Can somebody explain why it happened and is there any other method to make it with loop instead of split().reverse().join()
Here is my code:
var n = 352, reverse = 0, remainder;
while (n>0) {
remainder = n%10;
reverse = reverse * 10 + remainder;
n = n / 10;
}
console.log(reverse);

The only missing term is rounding of the number to nearest integer.
Here is updated code.
var n = 352, reverse = 0, remainder;
while (n>0) {
remainder = n%10;
reverse = reverse * 10 + remainder;
n = Math.floor(n / 10);
}
console.log(reverse);

Use:
n = parseInt(n / 10);
instead of
n = n / 10;

Related

iterating from 0 to 100 and printing the sum of all evens and the sum of all odds as array

I am trying to iterate from 0 to 100 and trying to print the sum of even numbers and odd numbers as array, like this [2550, 2500].
let m=0;
for(let i=0;i<=100;i++) {
m = m + i;
}
console.log(Array.from(String(m)));
but this code is returning  ['2', '5', '0', '0']
Can anyone please show me how can I print both the sums as array?
Also if someone could help me with the code for putting this code into other conditional statement so that I can get both, the sum of odd numbers and sum of even numbers. I am facing issue deciding which one to use here, else if, if else....
You just need to check the reminder of the number(i), if it's zero then it is even else it's odd.
let m=0,k=0;
for(let i=0;i<=100;i++)
{
if(i%2==0)m+=i
else k+=i;
}
then console.log([m,k]);
As you tagged the question with math I think the mathematics of triangular numbers should be mentioned here:
function sumOddEven(n) {
const floor = Math.floor(n / 2);
const ceil = Math.ceil(n / 2);
return [ceil * ceil, floor * (1 + floor)];
}
console.log(sumOddEven(100))
Without function:
const n = 100; // Example
const floor = Math.floor(n / 2);
const ceil = Math.ceil(n / 2);
const arr = [ceil * ceil, floor * (1 + floor)];
console.log(arr)
Your code is calculating the sum of all the numbers in the range of 0-100.
m will have the sum of range(0-100) that is 5050.
for(let i=0;i<=100;i++) {
m = m + i;
}
This line will split the digits of variable m and make an array of it.
console.log(Array.from(String(m)));
['5','0','5','0']
You can have two variables for even_sum and odd_sum and then check if i is odd then add it to odd_sum else add it to even_sum.
let even_sum=0;
let odd_sum=0;
for(let i=0;i<=100;i++) {
if (i%2==0)
even_sum+=i;
else
odd_sum+=i;
}
To return the values as array, you can do -
console.log([even_sum,odd_sum])
Use an array to sum each parity individually.
m=[0,0];
for (i=0;i<101;i++)
m[i%2]+=i;
console.log(m);

Rounding-off from whole numbers to whole numbers in JavaScript?

So I have some numbers x = 320232 y = 2301 z = 12020305. I want to round these numbers off using JavaScript so that they become x = 320000 y = 2300 z = 12000000.
I tried Math.round and Math.floor but turns out that they only work with decimal values like
a = 3.1; Math.round(a); // Outputs 3 and not whole numbers.
So my question is can we round of whole numbers using JavaScript and If yes then how?
Edit: I want it to the round of to the starting 3 digit places as seen in the variables above. Like If there was another variable called c = 423841 It should round off to become c = 424000.
You could work with the logarithm of ten and adjust the digits.
const
format = n => v => {
if (!v) return 0;
const l = Math.floor(Math.log10(Math.abs(v))) - n + 1;
return Math.round(v / 10 ** l) * 10 ** l;
};
console.log([0, -9876, 320232, 2301, 12020305, 123456789].map(format(3)));
The solution is to first calculate how many numbers need to be rounded away, and then use that in a round.
Math.round(1234/100)*100 would round to 1200 so we can use this to round. We then only need to determan what to replace 100 with in this example.
That is that would be a 1 followed by LENGTH - 3 zeros. That number can be calculated as it is 10 to the power of LENGTH - 3, in JS: 10 ** (length - 3).
var x = 320232;
var y = 2301;
var z = 12020305;
function my_round(number){
var org_number = number;
// calculate integer number
var count = 0;
if (number >= 1) ++count;
while (number / 10 >= 1) {
number /= 10;
++count;
}
// length - 3
count = Math.round(count) - 3;
if (count < 0){
count = 0;
}
// 10 to the power of (length - 3)
var helper = 10 ** count;
return Math.round(org_number/helper)*helper;
}
alert(my_round(x));
alert(my_round(y));
alert(my_round(z));
It is not the prettiest code, though I tried to make it explainable code.
This should work:
function roundToNthPlace(input, n) {
let powerOfTen = 10 ** n
return Math.round(input/powerOfTen) * powerOfTen;
}
console.log([320232, 2301,12020305, 423841].map(input => roundToNthPlace(input, 3)));
Output: [320000, 2000, 12020000, 424000]

Problem calculating the sum of arithmetic progression when using prompt() [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Javascript: "+" sign concatenates instead of giving sum of variables
(4 answers)
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I am trying this code to add a number starting from 1 to n using this mathematical equation:n = n(n+1) /2
var n = prompt("enter a number");
function adding(n) {
let N = n * (n + 1) / 2;
return N;
}
alert(adding(n));
but it's not working in prompt. It works like this:
function adding(n) {
let N = n * (n + 1) / 2;
return N;
}
console.log("answer", adding(100));

Reverse Integer Without converting to a string Javascript? [duplicate]

This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 2 years ago.
So i am trying to reverse an integer and so far the code works but i am trying to find a solution to reverse the integer without converting into a string first? Any help would be appreciated. This is my code snippet so far to reverse the integer.
function reverseInt(num) {
const reversed = num.toString().split('').reverse().join('')
return parseInt(reversed) * Math.sign(num)
}
console.log(reverseInt(-500));
I am trying to do it using javascript.
Try this:
function reverseInt(number) {
var isNegative = number < 0 ? true : false;
if(isNegative)
number = number * -1;
var reverse = 0, lastDigit = 0;
while (number >= 1) {
reverse = Math.floor(reverse * 10 + (number % 10));
number = number / 10;
}
return isNegative == true ? reverse*-1 : reverse;
}
console.log(reverseInt(-500));
console.log(reverseInt(501));

How to convert this Pascal Code to JavaScript?

I am trying to make simple JS code to find out the amount a number from 1 to 9 occurs in a given string. I have this Pascal code that works:
Var n,i:longint;
A:array[0..9] of byte;
Begin
write('Введите число: ');readln(n);
While n>0 do
Begin
A[n mod 10]:=A[n mod 10]+1;
n:=n div 10;
End;
For i:=0 to 9 do
writeln('The number ',i,' occurs ',A[i],' amount of times');
readln;
End.
In JS I ended up with this, but that seems to have a never-ending loop:
function plosh(form) {
var list = new Array(9);
var n = form.a.value;
while (n>0) {
a = n % 10;
list[a] = list[a]+1;
n = n % 10;
}
for (var i=0; i<=9; i++)
{
alert("Цифра"+i+"встречается"+A[i]+"раз");
}
}
Would appreicate any help on where I am going wrong with this. Thanks in advance!
n = n % 10 leaves n unchanged as soon as it's lower than 10, so it will usually never reach 0, hence the endless loop.
The div operator in Pascal makes an integral division.
Change
n = n % 10
to
n = Math.floor( n / 10 );
You also have another problem : you're not properly initializing your array so you're adding 1 to undefined. Fix that like this :
function plosh(form) {
var a,
list = [],
n = form.a.value;
while (n>0) {
a = n % 10;
list[a] = (list[a]||0)+1;
n = Math.floor( n / 10 );
}
for (var i=0; i<=9; i++) {
console.log("Цифра"+i+"встречается"+A[i]+"раз"); // <- less painful than alert
}
}
n:=n div 10;
was translated as:
n = n % 10;
but should be:
n = Math.floor(n / 10);
Edit: Also, you define an array [0..9] in Pascal, which means 10 elements. When you call Array(9) you only create 9 elements.

Categories

Resources