This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 8 years ago.
I've used .toString(2) to convert an integer to a binary, but it returns a binary only as long as it needs to be (i.e. first bit is a 1).
So where:
num = 2;
num.toString(2) // yields 10.
How do I yield the octet 00000010?
It's as simple as
var n = num.toString(2);
n = "00000000".substr(n.length) + n;
You could just use a while loop to add zeroes on the front of the result until it is the correct length.
var num = 2,
binaryStr = num.toString(2);
while(binaryStr.length < 8) {
binaryStr = "0" + binaryStr;
}
Try something like this ...
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
... then use it as ...
pad(num.toString(2), 8);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is my answer. However, I couldn't pass the test case for "11".
I couldn't find what is wrong in the code. Please help! Thank you!
/**
* #param {number} x
* #return {boolean}
*/
var isPalindrome = function(x) {
if (x === 0) {
return true;
}
if (x < 0 || x % 10 === 0) {
return false;
}
let rev = 0;
while (x > rev) {
pop = x % 10;
x = x / 10;
rev = (rev * 10) + pop;
}
if (x === rev || x === rev / 10) {
return true;
}
else {
return false;
}
};
Finding palindromes is inherently something which you would typically do using strings, not numeric variables, so I suggest converting your number to a string, and going from there:
var isPalindrome = function(x) {
x = x + ""; // convert to string, if x be a number
var isPalindrome = true;
for (i = 0; i < x.length/2; i++) {
if (x.substring(i, i+1) != x.substring(x.length-1-i, x.length-i)) {
isPalindrome = false;
break;
}
}
return isPalindrome;
}
console.log(isPalindrome(1234321));
console.log(isPalindrome(1234329));
The strategy here is just to iterate half the string, and assert that each character matches its counterpart in the other half. Note that we don't need to check the middle character, in the case of an input with an odd number of characters.
Your question seems to be LeetCode 9 and in the discussion board, there are good accepted solutions such as:
JavaScript
var isPalindrome = function(x) {
if (x < 0)
return false;
let reversed = 0;
for (let i = x; i > 0; i = Math.floor(i / 10))
reversed = reversed * 10 + i % 10;
return reversed === x;
};
Python
class Solution:
def isPalindrome(self, x):
if x < 0 or (x > 0 and not x % 10):
return False
return str(x) == str(x)[::-1]
Java
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0))
return false;
int reversed = 0;
while (x > reversed) {
reversed = reversed * 10 + x % 10;
x /= 10;
}
return (x == reversed || x == reversed / 10);
}
}
There is another similar isPalindrome question that if you might be interested, I've just copied below:
JavaScript I
var isPalindrome = function(s) {
var original = s.replace(/\W/g, ''); // means NON-WORD characters
var reversed = original.split('').reverse().join('');
return original.toLowerCase() == reversed.toLowerCase();
};
JavaScript II
var isPalindrome = function(s) {
var original = s.replace(/[^a-z0-9]/isg, '');
var reversed = original.split('').reverse().join('');
return original.toLowerCase() == reversed.toLowerCase();
};
Java
class Solution {
public boolean isPalindrome(String s) {
String original = s.replaceAll("(?i)[^a-z0-9]", "").toLowerCase();
String reversed = new StringBuffer(original).reverse().toString();
return original.equals(reversed);
}
}
Python
class Solution:
def isPalindrome(self, s):
s = ''.join(re.findall(r'(?is)[a-z0-9]+', s)).lower()
return s == s[::-1]
\W (non-word-character) matches any single character that doesn't match by \w (same as [^a-zA-Z0-9_]).
Reference
You can find additional explanations in the following links:
LeetCode 9 JavaScript Discussion Board
LeetCode 125 JavaScript Discussion Board
Using string for checking palindrome is very easy and straight forward. Having said that if you want to see how you can do it without changing number to string,
First initialise an variable start with Math.pow(10, digit count-1)
Loop till the value of start is greater than 0
inside loop compare the first and last digit if they are not equal return false
on each iteration remove the first and last digit from x and reduce start by 100
var isPalindrome = function(x) {
// as per question on leetcode negative values cannot be palindrome
if( x < 0) {
return false
}
x = Math.abs(x)
// to get the digits from start we need to get log10 of given value
let len = Math.ceil( Math.max( Math.log10(x), 1 ) ) - 1
let start = Math.pow(10, len)
while(start){
// compare first digit with the last digit
if(Math.floor(x/start) != (x % 10)){
return false
}
// remove first digit of current x
x = x % start
// remove last digit of current x
x = Math.floor(x/10)
// reduce start by 100 as we removed 2 digits
start = Math.floor(start / 100)
}
return true
};
console.log(isPalindrome(1))
console.log(isPalindrome(1221))
console.log(isPalindrome(-121))
console.log(isPalindrome(12341))
console.log(isPalindrome(100111))
Note:- We do (digit count - 1) so that we can capture the first digit
Original leetcode question link
This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 3 years ago.
Question:
I have 12345678 as text how to get 12,345,678? And as many more numbers between single quote?
I tried this code, but it's qualified for 123456.length <= 6 :-
if (int.length > 3) {
int = int.substr(0, int.length - 3) + "," + int.substr(int.length - 3, 3);
}
function comma(num) {
var newNum;
var len = num.length;
if (len > 3) {
var comNo = len % 3;
newNum = num
.split("")
.reverse()
.join("")
.match(/.{1,3}/g)
.map(function(current) {
return current
.split("")
.reverse()
.join("");
});
newNum.reverse();
return newNum.join();
} else {
return num;
}
}
int = comma(int);
I've been trying to make a little program that can compute the n-th digit of pi.
After a few searches I've found that the most common formula is the BBP formula, wich is n-th digit = 16^-n[4/(8n + 1)-2/(8n + 4)-1/(8n + 5)-1/(8n + 6)].
The output is in base 16.
My code is the following:
function run(n) {
return Math.pow(16, -n) * (4 / (8 * n + 1) - 2 / (8 * n + 4) - 1 / (8 * n + 5) - 1 / (8 * n + 6));
}
function convertFromBaseToBase(str, fromBase, toBase) {
var num = parseInt(str, fromBase);
return num.toString(toBase);
}
for (var i = 0; i < 10; i++) {
var a = run(i);
console.log(convertFromBaseToBase(a, 16, 10));
}
So far, my output is the following:
1:3
2:0
3:0
4:0
5:1
6:7
7:3
8:1
9:7
10:3
Obviously, these are not the 10 first digits of PI.
My understanding is that values get rounded too often and that causes huge innacuracy in the final result.
However, I could be wrong, that's why I'm here to ask if I did anything wrong or if it's nodejs's fault. So I would loove if one of you guys have the answer to my problem!
Thanks!!
Unfortunately, 4/(8n + 1) - 2/(8n + 4) - 1/(8n + 5) - 1/(8n + 6) does not directly return the Nth hexadecimal digit of pi. I don't blame you, I made the same assumption at first. Although all the terms do indeed sum to pi, each individual term does not represent an individual hexadecimal digit. As seen here, the algorithm must be rewritten slightly in order to function correctly as a "digit spigot". Here is what your new run implementation ought to look like:
/**
Bailey-Borwein-Plouffe digit-extraction algorithm for pi
<https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula#BBP_digit-extraction_algorithm_for_.CF.80>
*/
function run(n) {
var partial = function(d, c) {
var sum = 0;
// Left sum
var k;
for (k = 0; k <= d - 1; k++) {
sum += (Math.pow(16, d - 1 - k) % (8 * k + c)) / (8 * k + c);
}
// Right sum. This converges fast...
var prev = undefined;
for(k = d; sum !== prev; k++) {
prev = sum;
sum += Math.pow(16, d - 1 - k) / (8 * k + c);
}
return sum;
};
/**
JavaScript's modulus operator gives the wrong
result for negative numbers. E.g. `-2.9 % 1`
returns -0.9, the correct result is 0.1.
*/
var mod1 = function(x) {
return x < 0 ? 1 - (-x % 1) : x % 1;
};
var s = 0;
s += 4 * partial(n, 1);
s += -2 * partial(n, 4);
s += -1 * partial(n, 5);
s += -1 * partial(n, 6);
s = mod1(s);
return Math.floor(s * 16);
}
// Pi in hex is 3.243f6a8885a308d313198a2e037073...
console.log(run(0) === 3); // 0th hexadecimal digit of pi is the leading 3
console.log(run(1) === 2);
console.log(run(2) === 4);
console.log(run(3) === 3);
console.log(run(4) === 15); // i.e. "F"
Additionally, your convertFromBaseToBase function is more complicated than it needs to be. You have written it to accept a string in a specific base, but it is already being passed a number (which has no specific base). All you should really need is:
for (var i = 0; i < 10; i++) {
var a = run(i);
console.log(a.toString(16));
}
Output:
3
2
4
3
f
6
a
8
8
8
I have tested this code for the first 30 hexadecimal digits of pi, but it might start to return inaccurate results once Math.pow(16, d - 1 - k) grows beyond Number.MAX_SAFE_INTEGER, or maybe earlier for other reasons. At that point you may need to implement the modular exponentiation technique suggested in the Wikipedia article.
This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 3 years ago.
Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.
NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the - and read it.
UPDATE: Small one-liner function using the ES2017 String.prototype.padStart method:
const zeroPad = (num, places) => String(num).padStart(places, '0')
console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"
Another ES5 approach:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
You could extend the Number object:
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
Examples:
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
From https://gist.github.com/1180489
function pad(a, b){
return(1e15 + a + '').slice(-b);
}
With comments:
function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
).slice(-b) // cut leading "1"
}
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}
Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:
pad.zeros = new Array(5).join('0');
function pad(num, len) {
var str = String(num),
diff = len - str.length;
if(diff <= 0) return str;
if(diff > pad.zeros.length)
pad.zeros = new Array(diff + 1).join('0');
return pad.zeros.substr(0, diff) + str;
}
If the padding count is large and the function is called often enough, it actually outperforms the other methods...
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript adding zeros to the beginning of a string (max length 4 chars)
javascript format number to have 2 digit
How can I format number to 3 digits like..
9 => 009
99 => 099
100 => 100
This is trivial.
var num = 9;
num = ""+num;
while(num.length < 3) num = "0"+num;
You can make this into a function easily yourself.
function pad(number, length)
{
var result = number.toString();
var temp = length - result.length;
while(temp > 0)
{
result = '0' + result;
temp--;
}
return result;
}
Surely you need to convert those numbers in strings, because numbers datatype don't "support" initial zeros.
You can toString() the number, then check his length (NUMLENGTH), if it's less than the total number of digits you need (MAXDIGITS) then prepend MAXDIGITS-NUMLENGTH zeros to the string.
http://jsfiddle.net/K3mwV/
String.prototype.repeat = function( num ) {
return new Array( num + 1 ).join( this );
}
for (i=1;i <= 100;i++) {
e = i+'';
alert('0'.repeat(3 - e.length)+i);
}
function padZeros(zeros, n) {
// convert number to string
n = n.toString();
// cache length
var len = n.length;
// if length less then required number of zeros
if (len < zeros) {
// Great a new Array of (zeros required - length of string + 1)
// Then join those elements with the '0' character and add it to the string
n = (new Array(zeros - len + 1)).join('0') + n;
}
return n;
}