How to split numbers into individual - javascript

I have this whole number 75892. i want to split it in individual and then add below is my code. it works fine but is there any other solution to minimize my code? thanks
var x=75892;
var d,ans=0;
while(x!=0){
d=x%10;
ans=ans+d;
x=parseInt(x/10);
}
document.write("SUM:"+ans);

That approach is fine other than the parseInt part. parseInt will first convert the number to string, then parse that string. You wanted Math.floor:
x = Math.floor(x / 10);
You can also use += and just generally there are a couple of shortcuts you could take:
var x = 75892;
var ans = 0;
while (x != 0) {
ans += x % 10;
x = Math.floor(x / 10);
}
document.write("SUM:" + ans);
Another approach would be to go through the digits, e.g. a string-based approach instead of a math-based one. But frankly, I don't think it would be better.

You wanted shorter - here's a one-line ES6 version:
var ans = [...(String(x))].map(Number).reduce((p, c) => p + c);
Use spread on a stringified version of x, convert them to numbers, then use reduce to sum the numbers.
DEMO

var x="" + 75892;
var sum = 0;
for( var i = 0; i < x.length; i++ )
{
sum += parseInt( x[i] );
}
console.log( "sum: " + sum );
Please try this once.

Use, please review Sum of a string of one-digit numbers in javascript?
var sum = function(a,b){return a+b}
function stringSum(s) {
var int = function(x){return parseInt(x,10)}
return s.split('').map(int).reduce(sum);
}
document.write(stringSum("75892"))

You just need to split the variable-
var x=75892;
var arr = x.split('');
var count=0;
for (var i=arr.length; i--;) {
count = count+parseInt(arr[i]);
}

The following code is, when i was thought in college days, Now share with you. Beauty is there is no loop.
var x=75892;
var d,ans = 0;
x = parseInt(x);
if(x < 0){
x = -1 * x;
}
if(x > 0){
d = x % 9;
if(d == 0){
ans = 9;
}else{
ans = d;
}
}
document.write("SUM:"+ans);

If you're asking if there's a smarter way, than just peeling off digits at the end, then no - not in the decimal system at least.
Unless you want to reduce to a single digit (eg. 75892 -> 31 -> 4) in which case
function(d){
if(d === 0){
return 0;
}
var m = d%9;
return m === 0 ? 9 : m;
}
will do the trick

Related

How to "round" number, by putting zeros after the 2nd digit in javascript

I would like to "round" an integer number, by swapping all the digits after the 2nd digit to zeros. Additionally, if the number has only 1 digit, then don't do anything, and if the number has 2 digits, then swap the 2nd digit to a 0.
Example:
3 => 3
22 => 20
754 => 750
8912 => 8900
Can this be achieved without truncating the number as a string, and then rebuilding the number with zeros?
You don't need to truncate the number as a string, it can be easily achieved via mathematical calculation. Also, changing number to string and then doing any operation will be an added overhead which is not required in this case.
Refer the code below, it's quite straight forward.
Hope this helps.
function changeNumber(num){
if(Math.floor(num/10) == 0){
return num;
} else if(Math.floor(num/1000) == 0){
return Math.floor(num/10)*10;
}
else{
return Math.floor(num/100)*100
}
}
console.log(changeNumber(3));
console.log(changeNumber(22));
console.log(changeNumber(754));
console.log(changeNumber(8923));
That will work with every base-10 number.
All is about a simple math operation: number - [rest of (number / base-10 of number)]
function round(n) {
if(n < 10) return n;
var d = getTenBase(n.toString().length - 1);
return n - (n % (10 * d));
}
function getTenBase(l) {
var d = 1;
for(var i = 2; i < l; i++) {
d *= 10;
}
return d;
}
console.log(round(3));
console.log(round(22));
console.log(round(768));
console.log(round(1657));
you can just find length and first two character after that take zero with valid length and concat both
var str = '8912';
var n = str.length;
if(n == 1)
{
print(str);
} else if(n==2) {
var strFirst = str.substring(0,1);
var str2 = '0';
var res = strFirst.concat(str2);
} else if(n>2) {
var strFirst = str.substring(0,2);
var i;
var strsec ='0';
for (i = 0; i < n-3; i++) {
strsec += 0 ;
}
var res = strFirst.concat(strsec);
}
print(res);

Javascript Integer Array Error

I'm making a function that takes in user input and must display it as 7 characters i.e. if 42.54 was entered it would display 0004254. My issue is that I'm taking an integer and applying it to an array causing an undefined error when applying the 0's
function BackDataDefaultInput() {
// Balance
var count;
var newNum = "";
var balanceText = document.getElementById('balanceNumBox').value;
count = balanceText.length;
while (count > 0 && count < 7) {
newNum += '0';
count++
}
var formattedBalance = parseInt(balanceText, 10) * 100;
for (var i = 0; i < balanceText.length; i++) {
formattedBalance[i] = new Array();
// Error here showing as undefined for formattedBalance[i]
newNum += formattedBalance[i];
}
This code worked before I had to multiply it by 100 to get the right format. as I was just appending two strings. Can somebody help me think of a solution?
Primitives (like numbers) are immutable; if you have
var formattedBalance = parseInt(balanceText, 10) * 100;
you can't proceed to reassign index properties like
formattedBalance[i] = new Array();
It would probably be easier to remove the (possible) period with a regex and use padStart rather than mess with arrays:
function BackDataDefaultInput() {
const balanceText = '42.54'; // document.getElementById('balanceNumBox').value;
console.log(
balanceText
.replace(/\./g, '')
.padStart(7, '0')
);
}
BackDataDefaultInput();
Try to use following function.
var balanceText = "42.54"; //document.getElementById('balanceNumBox').value;
var formattedBalance = balanceText * 100;
function formatInteger(str, max) {
str = str.toString();
return str.length < max ? formatInteger("0" + str, max) : str;
}
console.log(formatInteger(formattedBalance, 7));
Answer to my question in case it helps anyone that comes across this page:
function BackDataDefaultInput() {
var balanceText = document.getElementById('balanceNumBox').value;
var balance = parseFloat(balanceText) * 100;
balanceText = String(balance);
while (balanceText.length > 0 && balanceText.length < 7) {
balanceText = '0' + balanceText;
}
}

A code wars challenge

I have been struggling with this challenge and can't seem to find where I'm failing at:
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
If it is the case we will return k, if not return -1.
Note: n, p will always be given as strictly positive integers.
digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
I'm new with javascript so there may be something off with my code but I can't find it. My whole purpose with this was learning javascript properly but now I want to find out what I'm doing wrong.I tried to convert given integer into digits by getting its modulo with 10, and dividing it with 10 using trunc to get rid of decimal parts. I tried to fill the array with these digits with their respective powers. But the test result just says I'm returning only 0.The only thing returning 0 in my code is the first part, but when I tried commenting it out, I was still returning 0.
function digPow(n, p){
// ...
var i;
var sum;
var myArray= new Array();
if(n<0)
{
return 0;
}
var holder;
holder=n;
for(i=n.length-1;i>=0;i--)
{
if(holder<10)
{
myArray[i]=holder;
break;
}
myArray[i]=holder%10;
holder=math.trunc(holder/10);
myArray[i]=math.pow(myArray[i],p+i);
sum=myArray[i]+sum;
}
if(sum%n==0)
{
return sum/n;
}
else
{
return -1;
}}
Here is the another simple solution
function digPow(n, p){
// convert the number into string
let str = String(n);
let add = 0;
// convert string into array using split()
str.split('').forEach(num=>{
add += Math.pow(Number(num) , p);
p++;
});
return (add % n) ? -1 : add/n;
}
let result = digPow(46288, 3);
console.log(result);
Mistakes
There are a few problems with your code. Here are some mistakes you've made.
number.length is invalid. The easiest way to get the length of numbers in JS is by converting it to a string, like this: n.toString().length.
Check this too: Length of Number in JavaScript
the math object should be referenced as Math, not math. (Note the capital M) So math.pow and math.trunc should be Math.pow and Math.trunc.
sum is undefined when the for loop is iterated the first time in sum=myArray[i]+sum;. Using var sum = 0; instead of var sum;.
Fixed Code
I fixed those mistakes and updated your code. Some parts have been removed--such as validating n, (the question states its strictly positive)--and other parts have been rewritten. I did some stylistic changes to make the code more readable as well.
function digPow(n, p){
var sum = 0;
var myArray = [];
var holder = n;
for (var i = n.toString().length-1; i >= 0; i--) {
myArray[i] = holder % 10;
holder = Math.trunc(holder/10);
myArray[i] = Math.pow(myArray[i],p+i);
sum += myArray[i];
}
if(sum % n == 0) {
return sum/n;
} else {
return -1;
}
}
console.log(digPow(89, 1));
console.log(digPow(92, 1));
console.log(digPow(46288, 3));
My Code
This is what I did back when I answered this question. Hope this helps.
function digPow(n, p){
var digPowSum = 0;
var temp = n;
while (temp > 0) {
digPowSum += Math.pow(temp % 10, temp.toString().length + p - 1);
temp = Math.floor(temp / 10);
}
return (digPowSum % n === 0) ? digPowSum / n : -1;
}
console.log(digPow(89, 1));
console.log(digPow(92, 1));
console.log(digPow(46288, 3));
You have multiple problems:
If n is a number it is not going to have a length property. So i is going to be undefined and your loop never runs since undefined is not greater or equal to zero
for(i=n.length-1;i>=0;i--) //could be
for(i=(""+n).length;i>=0;i--) //""+n quick way of converting to string
You never initialize sum to 0 so it is undefined and when you add the result of the power calculation to sum you will continually get NaN
var sum; //should be
var sum=0;
You have if(holder<10)...break you do not need this as the loop will end after the iteration where holder is a less than 10. Also you never do a power for it or add it to the sum. Simply remove that if all together.
Your end code would look something like:
function digPow(n, p) {
var i;
var sum=0;
var myArray = new Array();
if (n < 0) {
return 0;
}
var holder;
holder = n;
for (i = (""+n).length - 1; i >= 0; i--) {
myArray[i] = holder % 10;
holder = Math.trunc(holder / 10);
myArray[i] = Math.pow(myArray[i], p + i);
sum = myArray[i] + sum;
}
if (sum % n == 0) {
return sum / n;
} else {
return -1;
}
}
Note you could slim it down to something like
function digPow(n,p){
if( isNaN(n) || (+n)<0 || n%1!=0) return -1;
var sum = (""+n).split("").reduce( (s,num,index)=>Math.pow(num,p+index)+s,0);
return sum%n ? -1 : sum/n;
}
(""+n) simply converts to string
.split("") splits the string into an array (no need to do %10 math to get each number
.reduce( function,0) call's the array's reduce function, which calls a function for each item in the array. The function is expected to return a value each time, second argument is the starting value
(s,num,index)=>Math.pow(num,p+index+1)+s Fat Arrow function for just calling Math.pow with the right arguments and then adding it to the sum s and returning it
I have created a code that does exactly what you are looking for.The problem in your code was explained in the comment so I will not focus on that.
FIDDLE
Here is the code.
function digPow(n, p) {
var m = n;
var i, sum = 0;
var j = 0;
var l = n.toString().length;
var digits = [];
while (n >= 10) {
digits.unshift(n % 10);
n = Math.floor(n / 10);
}
digits.unshift(n);
for (i = p; i < l + p; i++) {
sum += Math.pow(digits[j], i);
j++;
}
if (sum % m == 0) {
return sum / m;
} else
return -1;
}
alert(digPow(89, 1))
Just for a variety you may do the same job functionally as follows without using any string operations.
function digPow(n,p){
var d = ~~Math.log10(n)+1; // number of digits
r = Array(d).fill()
.map(function(_,i){
var t = Math.pow(10,d-i);
return Math.pow(~~((n%t)*10/t),p+i);
})
.reduce((p,c) => p+c);
return r%n ? -1 : r/n;
}
var res = digPow(46288,3);
console.log(res);

Convert huge if else statement into a loop in Javascript

I'm trying to format a number to be displayed in a more friendly way. At the moment, the code is really difficult to update and it's huge and clumsy.
function abb(){
if(m>=1 && m<999){
gold_display = m;
}else if(m>999 && m<999999){
var b = (m / 1000).toFixed(3);
gold_display = b+"k";
}else if (m>999999 && m<999999999){
var b = (m / 1000000).toFixed(3);
gold_display = b+"m";
}else if (m>999999999 && m<999999999999){
var b = (m / 1000000000).toFixed(3);
gold_display = b+"b";
}else if (m>999999999999 && m<99999999999999){
var b = (m / 1000000000000).toFixed(3);
gold_display = b+"t";
}
}
EDIT: THIS WOULD BE THE CODE:
function abb(){
if(m>=1 && m<1000){
gold_display = m;
}else if(m>999 && m<1000000){
var b = (m / 1000).toFixed(3);
gold_display = b+"k";
}else if (m>999999 && m<1000000000){
var b = (m / 1000000).toFixed(3);
gold_display = b+"m";
}else if (m>999999999 && m<1000000000000){
var b = (m / 1000000000).toFixed(3);
gold_display = b+"b";
}else if (m>999999999999 && m<100000000000000){
var b = (m / 1000000000000).toFixed(3);
gold_display = b+"t";
}
}
Yeah it's akward but it was the only solution that came up into my mind, is there a way to convert this into a loop and shrink the code?
I'm thinking in saving the letters "k", "m", "b","t" in an array because I want to go higher to "q", "qi","s", etc.
Thanks and sorry if the question is kinda stupid :(
Count how many times you need to divide by 1000 before you are under 1000
function bigNumber(big) {
let divisor = 1,
steps = 0,
small = big;
while (small >= 1000) {
divisor *= 1000;
small = big / divisor;
++steps;
}
return {steps, divisor, small};
}
let gold = 123456789,
foo = bigNumber(gold);
foo.small.toFixed(3) + ['', 'k', 'm', 'b', 't'][foo.steps];
// "123.457m"
It's not much but one simplification of your code is to eliminate the lower-bound checking since the if/else-if structure will take care of that:
function abb(m) {
if (m < 1) {
// some kind of error?
} else if (m < 1000) {
return m;
} else if (m < 1000000) {
return (m/1000).toFixed(3) + "k";
} else if (m < 1000000000) {
return (m/1000000).toFixed(3) + "m";
} else {
// and so on
}
}
You could do something more clever but I think it is probably best to be simple about it.
But if I understand your code correctly, you're trying to format numbers as thousands ("k"), millions ("m"), billions ("b") etc. Why not look at a library for this such as http://numeraljs.com/?
Specifically, you can use this code:
var numeral = require('numeral').language('en');
to import the numeral.js library, and then this code to perform the formatting:
var str = numeral(12345678).format("0.0a");// "12.3m"
var str = numeral(1234).format("0.0a");// "1.2k"
etc.
Full disclosure: this solution comes with the benefit of no for loop, but it does have some added complexity.
Take the logarithm of m. If 1 <= m< 999 then 0 <= exponent < 3. Similarly, if 1000 <= m < 999999 then 3 <= exponent < 6, and so on. You can see the pattern here, every prefix covers a range of 3 in the logarithmic scale. So you could do something like the following:
function abb(m){
var prefixes = ["","k","m","b","t"];
var log = Math.log10(m);
var prefixRange = parseInt(log/3, 10);
var prefix = prefixes[prefixRange];
return (m / Math.pow(1000, prefixRange)).toFixed(3) + prefix;
}
Actually, in the case of very large numbers, the above will break, so prefixRange = parseInt(log/3, 10) needs to be changed to prefixRange = Math.min(parseInt(log/3, 10), 4),to ensure we don't read beyond the length of array prefixes.
Also, notice that toFixed is not really to be trusted for large numbers in this case. 999999999 / 1000000 gives 1000.000, which I guess is not what you want. Better to round with floor in this case. Since you are only interested in the first digits (3 for the integer and 3 for the decimal part), you can first get those 6 digits and then divide by 1000.
A better function, addressing both issues is:
function abb(m){
var prefixes = ["","k","m","b","t"];
var log = Math.log10(m);
var prefixRange = Math.min(parseInt(log/3, 10), 4);
var prefix = prefixes[prefixRange];
return Math.floor((m / Math.pow(1000, prefixRange - 1)))/1000 + prefix;
}

Reverse decimal digits in javascript

How do I reverse the digits of a number using bitwise?
input:
x = 123;
output:
x = 321;
How Do this?
That's not inverting bits; that's reversing the order of decimal digits, which is completely different. Here's one way:
var x = 123;
var y = 0;
for(; x; x = Math.floor(x / 10)) {
y *= 10;
y += x % 10;
}
x = y;
If you actually want to invert bits, it's:
x = ~x;
As a function:
function reverse(n) {
for(var r = 0; n; n = Math.floor(n / 10)) {
r *= 10;
r += n % 10;
}
return r;
}
If you wanted to make a simple reversal:
var x = 123;
var y = x.toString();
var z = y.split("").reverse().join("");
var aa = Number(z);
document.write(aa);
http://jsfiddle.net/jasongennaro/gV39e/
Here is another way...
var reversed = num.toString().split('').reverse().join('');
jsFiddle.
If you wanted it again as a Number, use parseInt(reversed, 10). Keep in mind though, leading 0s are not significant in a decimal number, and you will lose them if you convert to Number.
you also use this function
function myfunction(a){
var x=a.toString();
var y= x.split("");
var z=y.reverse();
var result=z.join("");
return result;
}
myfunction(123);
Simple and quick solution: Let's assume that you want to reverse a number 4546. You will take the reminder from each division by 10 and append it to the result until the number is > 0. And simultaneously updating the num variable by dividing it by 10.
var x = '';
var num = 4546;
while(num>0){
x = x + (num%10);
num = parseInt(num/10);
}
console.log(x);
Reversing The Positive/ Negative Integer Number
function reverseInt(n) {
return parseInt(n.toString().split('').reverse().join()) * Math.sign(n)
}
If n is -5, then Math.sign(n)==> will return -1
If n is 5, then Math.sign(n)==> will return 1
Here are reversible array functions in JavaScript that handle integers or strings:
function reverse(array)
{
var left = null;
var right = null;
var length = array.length;
for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
{
var temporary = array[left];
array[left] = array[right];
array[right] = temporary;
}
return array;
}
function toDigitsArrayFromInteger(integer, isReverse)
{
var digits = [];
if (integer > 0)
{
var floor = window.Math.floor;
while (integer > 0)
{
digits.push(floor(integer % 10));
integer = floor(integer / 10);
}
// Array is populated in reverse order. Un-reverse it to make it normal.
if (!isReverse)
{
digits = reverse(digits);
}
}
else if (integer < 0)
{
digits = toDigitsArrayFromInteger(-integer, isReverse);
}
else if (integer === 0)
{
digits.push(0);
}
return digits;
}
function toDigitsArrayFromString(string, isReverse)
{
var digits = [];
string += ""; // Coerce to string.
var i = null;
var length = string.length;
for (i = 0; i < length; i += 1)
{
var integer = parseInt(string.charAt(i), 10);
if (isFinite(integer))
{
digits.push(integer);
}
}
if (isReverse)
{
digits = reverse(digits);
}
return digits;
}
Once you have the digits as an array, you can reverse the array easily to get the digits starting from the left or from the right.
The string function is more versatile because it can find any digit in a string, whereas the integer function is limited to integers.
Benchmarks:
http://jsperf.com/todigitsarray
The benchmarks between the two functions show that in Firefox 10 and Chrome 12, the string function is 30% to 60% faster than the integer function. In Opera 12, the integer function is slightly faster by about 10%.
//reverse integer
const revInt = (num)=>{
//turn into string
if(Math.sign(num)===1)
return parseInt(num.toString().split('').reverse().join(''));
else return -1*parseInt(num.toString().split('').reverse().join(''));
}
console.log(revInt(-501));
<html>
<script>
function reverseInt(n){
var r=0;
while(n!=0){
r*=10;
r+=n%10;
n=Math.floor(n/10);
}
return r;
}
</script>
</html>
try this
var n = 352;
function loop(n, r){
if(!n) return r;
r = (r ? r * 10 : 0) + n % 10;
return loop(Math.floor( n / 10), r);
}
console.log(loop(n));
OK, how about using and chaining these popular tricks in JavaScript in one-line function as below...
const reverseNum = num => +("" + ~~num.split("").reverse().join(""));
And call it like these:
reverseNum(123); //321
reverseNum(423.09); //324
reverseNum(23305.1); //50332
reverseNum(89112); //21198
reverseNum(568434.2389); //434865
This takes Number x as a parameter and returns the reversed number.
const reverse = (x) => Number(x.toString().split("").reverse().join(""));
Memory Usage: 35.3 MB, less than 100.00% of JavaScript online submissions for Reverse Integer on leetcode.com.
Runtime: 80 ms, faster than 61.48% of JavaScript online submissions for Reverse Integer.
Time complexity is O(log10(n)).
function reverse(x) {
let rev = 0;
const isNegative = Math.sign(x) === -1;
const isOverflow = n => n > 2**31;
x = Math.abs(x);
while (x) {
let pop = x % 10;
x = Math.floor(x / 10);
rev = rev * 10 + pop;
if (isOverflow(rev)) {
return 0;
}
}
return isNegative ? rev * -1 : rev;
}
The code block below should do the trick
<script type = "text/javascript">
var input;
input=window.prompt ("Please enter a number to be reversed.");
x=input.length;
while(x > 0)
{
x=x-1;
document.write(input[x]);
}
</script>

Categories

Resources