How to calculate the six least significant numbers of a big integer - javascript

I am writing some code to get the six least significant digits of a number.
Example: For N = 14930352, the least significant digits would be 930352 and for
N = 102334155, answer is 334155
Which one can do by N%1000000.
For 354224848179262000000 the answer is 915075, which I am getting wrong answer by using above method, I am getting 997056.

One way you could do is by converting this number to string, slicing the last 6 digits and convert back to number.

`
let leastSignificantDigits = value => {
const valueArr = [...`${value}`];
return valueArr.slice(valueArr.length-6).join('');
}
leastSignificantDigits(14930352)
'930352'
leastSignificantDigits(102334155)
'334155'

Related

Using Javascript parseInt returns a different value

I'm not entirely sure why the string "6145390195186705543" is outputting 6145390195186705000, at first reading through the threads it may be the base radix but even tinkering around with that still gives me the same results, can anyone help explain because I do believe this is not a bug, but I'm not entirely sure what's the explanation here.
const digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
const val1 = digits.join('') // string "6145390195186705543"
const test1 = Number(val1) // outputs 6145390195186705000
const test2 = parseInt(val1) // outputs 6145390195186705000
It's not an issue with parseInt. If you were to create the same number from a number literal, you'd get the same problem.
This happens because JavaScript stores numbers as double prescision floats, which offer approximately 16 significant decimal digits.
The only way to fix this is to not use the Number type. JavaScript has another number type, BigInt, which offers arbitrary precision integers. Here's how you can do it with it:
const digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
const val1 = digits.join('')
const test3 = BigInt(val1) // 6145390195186705543n - The n at the end means it's a BigInt

Plus One - Leet code Problem (easy )- All the test cases passed except one in javascript

I guess my solution has passed all the test cases but failed on one.
Plus one- leetcode problem
Problem:
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
Constraints:
1 <= digits.length <= 100
0 <= digits[i] <= 9
digits does not contain any leading 0's.
My solution:
var plusOne = function(digits) {
let arrToStr=digits.join('');
arrToStr++;
let strToArr = arrToStr.toString().split('').map((x)=>parseInt(x));
return strToArr;
};
Failed on this test cases:
Input:
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output:
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected:
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
Is there anything I am doing wrong? Or Is it because of javascript? As I have read that javascript is not good for Competitive programming because it has some drawbacks.
Integer in JavaScript can only represent up to 9,007,199,254,740,991 (https://stackoverflow.com/a/49218637/7588455)
6,145,390,195,186,705,543 is larger than that.
I recommend using BigInt as an alternative.
A possible solution would look like this:
https://pastebin.com/NRHNYJT9 (Hidden so I don't spoiler you)
Here is my solution, though it might not exactly shine concerning its performance:
function plusOne(digits: number[]): number[] {
let digitsCombined = BigInt(digits.join(''));
return (++digitsCombined).toString().split('').map(Number);
};

Recurring Numbers: How to get a non-rounded recurring number when dividing a number by another number?

I am trying to solve a particular JavaScript exercise involving recurring numbers and in doing so I need to work with recurring numbers to a good amount of decimal places.
Currently I am using:
function divide(numerator, denominator){
var num = (numerator/parseFloat(denominator);
}
// 7/11 = 0.6363636363636364
// 5/3 = 1.6666666666666667
// 3/8 = 0.375
As you can see, the results of the operation that contain recurring digits are returned with the final digit rounded. It is tempting to simply convert to array and pop() the last digit of each number but this leads to problems when we run into numbers that are not recurring such as 3/8 =0.375.
How can I divide two numbers and get a result that such as 5/3 = 1.666666666666666 ? (essentially the last digit is rounded down and never rounded up)
Thanks for your help.
For simple cases, I typically use the round-to npm package:
import roundTo from 'round-to';
const num = 5/3; // 1.6666666666666667
// set your desired number of decimal places:
const numDecimalPlaces = (num + "").split(".")[1].length;
// Based on your question, I think this is what you are trying to achieve:
const roundedDown = roundTo.down(num, numDecimalPlaces - 1); // 1.6666666666666667
// You can also do these:
const rounded = roundTo(num, numDecimalPlaces); // 1.6666666666666667
const roundedUp = roundTo.up(num, numDecimalPlaces); // 1.6666666666666667
If you don't want to install their package, you can copy their implementation from Github. Their source code is pretty easy to follow.

How can I find the missing integer in a string of random non-repeating integers in a range

I'm having trouble even beginning to think of how to do this.
I need to find a missing number in a string of random numbers that don't have separators.
Here's an example: 14036587109. In this example, the missing number is 2, the range is 0-10 (inclusive).
How can I write a JavaScript/Node.JS program to solve this?
The part I can't figure out is how the program separates the numbers; In the example above, how would the program know that the number 10 (before the last number) isn't the numbers 1 and 0.
There are two things we know about the missing integer: the total number of digits in the input tells us the number of digits in the missing integer, and (as #samgak mentioned in a comment) counting the occurrences of each digit in the input tells us which digits the missing integer is made of. This may give us a quick path to the solution, if one of the permutations of those digits is missing from the input. If it doesn't, then:
Find the integers from highest to lowest number of digits; if the range is e.g. 0-999, then search the 3-digit integers first, then 2, then 1.
If an integer is only present at one location in the input, mark it as found, and remove it from the input.
Then, start again with the longest integers that haven't been found yet, and look at the ones that are present at two locations; try both options, and then check whether all other integers that rely on the digits we're using are also present; e.g. if 357 is present at two locations:
... 1235789 ... 2435768 ...
357 357
23 43
123 243
235 435
578 576
78 76
789 768
When trying the first location for the 357, check whether there is another possibility for 23, 123, 235, 578, 78, and 789. For the second location, check 43, 243, 435, 576, 76 and 768.
If these checks show that only one of the options is possible, mark the number as found and remove it from the input.
Go on to do this for shorter integers, and for integers that are present at 3, 4, ... locations. If, after doing this to a certain point, there is still no result, you may have to recursively try several options, which will quickly lead to a huge number of options. (With especially crafted large input, it is probably possible to thwart this method and make it unusably slow.) But the average complexity with random input may be decent.
Actually, when you find an integer that is only present in one location in the input, but it is a permutation of the missing digits, you should not remove it, because it could be the missing integer. So the algorithm might be: remove all integers you can unequivocally locate in the input, then try removing all possible missing integers one by one, and look for inconsistencies, i.e. other missing numbers that don't have the correct length or digits.
It's all a question of heuristics, of course. You try something simple, if that doesn't work you try something more complicated, if that doesn't work, you try something even more complicated... and at each step there are several options, and each one could be optimal for some input strings but not for others.
E.g. if the range is 0-5000, you'd start by marking the 4-digit integers that are only present at one location. But after that, you could do the same thing again (because integers that were present twice could have had one of their options removed) until there's no more improvement, or you could check integers that are present twice, or integers that are present up to x times, or move on to 3-digit integers... I don't think there's a straightforward way to know which of these options will give the best result.
This solution should work for any input string and any start/end range:
We can think about the numbers in the string as a pool of digits that we can choose from. We start at startRange and go through to endRange, looking for each number along the way in our pool of digits.
When we find a number that can be composed from our pool of digits, we delete those digits from our pool of digits, as those digits are already being used to form a number in our range.
As soon as we come across a number that cannot be composed from our pool of digits, that must be the missing number.
const str = "14036587109"; // input
const numsLeft = str.split("").map(num => parseInt(num)); // array of numbers
const startRange = 0;
const endRange = 10;
for(let i = startRange; i <= endRange ; i++) {
// check if number can be formed given the numbers left in numsLeft
const numFound = findNum(numsLeft, i);
if(!numFound) {
console.log("MISSING: " + i); // prints 2
break;
}
}
function findNum(numsLeft, i) {
// array of digits
const numsToFind = String(i).split("").map(num => parseInt(num));
// default is true, if all digits are found in numsLeft
let found = true;
numsToFind.forEach(num => {
// find digit in numsLeft
const numFoundIndex = numsLeft.indexOf(num);
if(numFoundIndex < 0) {
// digit was not found in numsLeft
found = false;
return;
} else {
// digit was found; delete digit from numsLeft
numsLeft.splice(numFoundIndex, 1);
}
});
return found;
}
var input = '10436587109';
var range = [10,9,8,7,6,5,4,3,2,1,0];
var expr1 = new RegExp(range.join('|'),'g');
var expr2 = new RegExp('[0-9]','g');
var a = input.match(expr1).map(Number).concat(input.match(expr2).map(Number));
var x = range.filter(function(i){ return a.indexOf(i)===-1; });

Remove last digits from an int

Can't seem to find a good answer to this question. How do I remove the last 11 digits from an int?
The id could be one or more numbers in the beginning but there will always be 11 digits following the id. There will always be an id in the beginning. {id}{11 digits}.
var getId = function (digits) {
// Do some stuff and return id
}
getId(110000000001); // Should return 1
getId(1110000000001); // Should return 11
getId(2010000000001); // Should return 20
Divide by 1e11 and take the floor:
var stripped = Math.floor(id / 1e11);
This avoids conversion to/from a string representation.
Note that the nature of JavaScript numerics is such that your "raw" values (the values with the 11 useless digits) can't have more than 5 digits in addition to those 11 before you'll start running into precision problems. I guess if you never care about the low-order 11 digits that might not be a problem.
Try this:
var str = 1100000000011;
var res = str.toString().substr(0, str.toString().length - 11);
Demo
You can convert your number to string and delete tailing digits:
digits.toString().replace(/\d{11}$/, '')
By the way, you better don't use ints (or to be precise, Numbers) because if number is greater than 2147483648 (by absolute value), it'll be represented internally as double resulting in precision loss. If don't need tailing digits, then it's okay — use division approach suggested in other answers (this one could break because of scientific notation). But if you want to keep all the data, you should represent your numbers with strings.
You can use division and 10^11 to do so.
Edit: my bad
var getId = function (digits) {
var id = parseInt((digits/(1e11)),0);
}
You can convert the number to a string and slice the last 11 characters from the end
parseInt( digits.toString().slice(0, -11) );
Using .slice( 0 , [ negative_number ]); will slice x characters from the end of the string
More information on .slice() Here

Categories

Resources