Case 1:
input: 145
output: 146
Case 2:
input 199
output 1001
Case 3:
input: 59
output 501
Case 4:
input: 99
output: 901
So the first number should never change.
Reason is the first number is a classification (1-9). The number following is serial numbers.
So 199 is classifcation '1' and serial number 99. The next serial number is 1001. Henche the odd logic (I didn't decide this).
Any smart way of doing this?
Convert the number to a string. Get the first digit as the first character of the string, and the rest as the remaining characters. If the rest is all 9, increment it to that many 0's + 1, otherwise just add 1 to it. Then concatenate this back with the original first digitl
function increment_serial(input) {
var str = input.toString();
var first = str[0];
var rest = str.substr(1);
if (rest.match(/^9+$/)) {
var newrest = rest.replace(/9/g, '0') + '1';
} else {
newrest = parseInt(rest, 10) + 1;
}
return first + newrest;
}
console.log(increment_serial(145));
console.log(increment_serial(199));
console.log(increment_serial(59));
console.log(increment_serial(99));
Have two variables, a prefix and the number:
var prefix = "5";
var number = 99;
var output = prefix + number;
alert(output);
number = number + 1;
output = prefix + number;
alert(output);
And here is the fiddle: https://jsfiddle.net/xedret/0ujgjsbj/
function incrementNumberLeavingFirst(number) {
var numberAsString = number+"";
incrementedNumber = parseInt(numberAsString.slice(1))+1
return parseInt(numberAsString[0]+incrementedNumber);
}
alert(incrementNumberLeavingFirst(599))
We take an integer, number, as the first parameter of our function. This is the number that we want to increment.
Adding a string to an integer in JavaScript converts the integer to a string, so we get the string version of the number parameter by adding an empty string to it, and store that in the variable numberAsString.
Then, we take all of that string except for the first character using numberAsString.slice(1), convert it to an integer using parseInt, and add one. This increments the number (excluding the first digit). We store the incremented number in a variable called incrementedNumber.
Finally, we concatenate the first digit of the number to the incremented number (note that the first digit is still a string, so this converts incrementedNumber to a string, and adds the first number to the start of that string. Then we convert the whole thing to an integer using parseInt, and return it.
Related
I'm trying to solve the following Leetcode 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].
Here's my code :
var plusOne = function(digits) {
let newDigit = digits.join('')
if (newDigit.length > 15) {
let digitLength = newDigit.length
let secondHalf = newDigit.slice(digitLength - 15, digitLength)
secondHalf = parseInt(secondHalf) + 1
secondHalf = Array.from(String(secondHalf), Number)
digits.splice(digitLength - 15, 15)
return digits.concat(secondHalf)
}
let Digit = parseInt(newDigit) + 1
const answer = Array.from(String(Digit), Number)
return answer
};
Works for many data sets. Get's the following error on the following set. Why :(
When you do parseInt(secondHalf), you're effectively dropping any leading zeros in that string, and as a result those zeros don't get included in the final array. The input digits are guaranteed not to have any leading zeros, but that doesn't mean that there won't be any leading zeros if you slice the string in the middle.
Also, even fixing that, what about input arrays that are longer than 30 characters?
Consider using a BigInt instead, it'll be a lot easier.
const plusOne = function(digits) {
const bigInt = BigInt(digits.join('')) + 1n;
return [...String(bigInt)].map(Number);
}
console.log(plusOne(
'590840235570031372488506112'.split('').map(Number)
));
I want to get a random double number (for example 4.58)
and put its digits to three variables - 4 to the first variable, 5 to the second variable and 8 to the third variable.
Not sure why you need this to be a floating-point number. Just create a three-digit number, convert it to a string, and split it into an array.
var numArr = (Math.floor(Math.random() * 900) + 100).toString().split('');
You can get at the numbers using the normal array method: numArr[0] etc.
To convert it to number, add a period in the first array position and then join it back to together:
numArr.splice(1, 0, '.');
var number = numArr.join('');
DEMO
Alternatively, see this SO question on how to create random floating-point numbers.
You could do something like this:
var number = 4.26; // Your generated double number
output = []; // Array to store each digit
sNumber = number.toString(); // Convert the double to a string so we can split it
for (var i = 0, len = sNumber.length; i < len; i += 1)
{
output.push(+sNumber.charAt(i));
}
console.log(output);
The output will be:
4, 2, 6
All numbers in JavaScript are doubles: that is, they are stored as 64-bit IEEE-754 doubles.
That is, the goal is not to get a "double": the goal is to get the string reprsentation of a number formatted as "YYY.XX". For that, consider Number.toFixed, for instance:
(100).toFixed(2)
The result is the string (not a "double"!) "100.00". The parenthesis are required to avoid a grammar ambiguity in this case (it could also have been written as 100.0.toFixed or 100..toFixed), but would not be required if 100 was in a variable.
Use this. I use .replace(/[.]/g,"") for removing ".".
http://jsfiddle.net/sherali/coyv3erf/2/
var randomNumber = Math.floor(Math.random() * 900) + 100;
numArr= randomNumber.toString().replace(/[.]/g,"").split("")
var number = numArr.join("");
console.log(numArr, number); // ["8", "4", "5"] 845
I have a value fetched from the database, it's like:
4.5 which should be 4.500
0.01 which should be 0.010
11 which should be 11.000
so I used this piece of code
sprintf("%.3f",(double)$html['camp_cpc'])
But here arised another problem. If $html['camp_cpc'] = '4.5234', then also it displays 4.523 instead of original value 4.5234
Also for other values with larger decimal like 0.346513, its only showing up to 0.346.
How can I solve this problem in JavaScript also?
Floats 4.5 and 4.500 correspond to the same number, so they cannot (and should not) be used/stored in a way that preserves the different representation. If you need to preserve the original representation given by a user, you need to store this field as a list (string) and convert to a float whenever you need the float value
In Javascript at least, this is an implementation of what I think you want:
function getValue(x, points) {
var str = x.toString();
// Convert to string
var idx = str.indexOf(".");
// If the number is an integer
if(!~idx) return str + "." + "0".repeat(points);
// Get the tail of the number
var end = str.substr(idx+1);
// If the tail exceeds the number of decimal places, return the full string
if(end.length > points) return str;
// Otherwise return the int + the tail + required number of zeroes
return str.substr(0, idx) + "." + end.substr(0, points) + "0".repeat(points-end.length);
}
console.log(getValue(4.5, 3)); //4.500
console.log(getValue(0.01, 3)); //0.010
console.log(getValue(11, 3)); //11.000
Working demo (Makes use of ES6 String.repeat for demonstration purposes)
The important thing to note here is that this is string manipulation. Once you start to say "I want the number to look like..." it's no longer a number, it's what you want to show the user.
This takes your number, converts it to the string and pads the end of the string with the appropriate number of zeroes. If the decimal exceeds the number of places required the full number is returned.
In PHP, use %0.3f — and you don't need to cast as (double)
<?php
echo sprintf("%0.3f", 4.5); // "4.500"
echo sprintf("%0.3f", 4.5234); // "4.523"
If you want to display 4 decimal places, use %0.4f
echo sprintf("%0.4f", 4.5); // "4.5000"
echo sprintf("%0.4f", 4.5234); // "4.5234"
To do this in JavaScript
(4.5).toFixed(3); // "4.500"
It could look sth. like this:
var n = [4.5234, 0.5, 0.11, 456.45];
var temp_n;
for(var i = 0; i < n.length; i++) {
temp_n = String(n[i]).split(".");
if(temp_n[1] == null || temp_n[1].length < 3) {
n[i] = n[i].toFixed(3);
}
}
How can I use javascript to randomly create a 20 digit string of numbers, each of the digits ranging only between 1 and 5?
An example would be: 52431425331425141521
As well as the logical algorithm I gave in my comment above, you could just use this one-liner:
var result = Math.floor(Math.random()*95367431640625).toString(5)
.split("").map(function(n) {return +n+1;}).join("");
Essentially, pick a random integer between 0 and 520-1, convert it to base 5, then increment all the digits by one, so they're all between 1 and 5 ^_^
EDIT: Just realised this won't handle low numbers too well. Try this:
var result = (
new Array(20).join("0")
+
Math.floor(Math.random()*95367431640625).toString(5)
).slice(-20).split("").map(function(n) {return +n+1;}).join(""));
This does basically the same, except it prepends 19 zeroes to the front of your number, then slices off the last 20 characters. This will allow it to handle leading zeroes correctly to give a 20-digit number in all cases.
You can use this:
function random_string()
{
var text = "";
var string = "12345";
for( var i=0; i < 20; i++ )
text += string.charAt(Math.floor(Math.random() * string.length));
return text;
}
random_string();
When I want to select the nth character, I use the charAt() method, but what's the equivalent I can use when dealing with integers instead of string values?
Use String():
var number = 132943154134;
// convert number to a string, then extract the first digit
var one = String(number).charAt(0);
// convert the first digit back to an integer
var one_as_number = Number(one);
It's a stupid solution but seems to work without converting to string.
var number = 123456789;
var pos = 4;
var digit = ~~(number/Math.pow(10,pos))- ~~(number/Math.pow(10,pos+1))*10;
You could convert the number to a string and do the same thing:
parseInt((number + '').charAt(0))
If you want an existing method, convert it to a string and use charAt.
If you want a method that avoids converting it to a string, you could play games with dividing it by 10 repeatedly to strip off enough digits from the right -- say for 123456789, if you want the 3rd-from-right digit (6), divide by 10 3 times yielding 123456, then take the result mod 10 yielding 6. If you want to start counting digits from the left, which you probably do, then you need to know how many digits (base 10) are in the entire number, which you could deduce from the log base 10 of the number... All this is unlikely to be any more efficient than just converting it to a string.
function digitAt(val, index) {
return Math.floor(
(
val / Math.pow(10, Math.floor(Math.log(Math.abs(val)) / Math.LN10)-index)
)
% 10
);
};
digitAt(123456789, 0) // => 1
digitAt(123456789, 3) // => 4
A bit messy.
Math.floor(Math.log(Math.abs(val)) / Math.LN10)
Calculates the number of digits (-1) in the number.
var num = 123456;
var secondChar = num.toString()[1]; //get the second character
var number = 123456789
function return_digit(n){
r = number.toString().split('')[n-1]*1;
return r;
}
return_digit(3); /* returns 3 */
return_digit(6); /* returns 6 */