Bit Pattern in JavaScript [duplicate] - javascript

This question already has answers here:
String Conversion in Javascript (Decimal to Binary)
(5 answers)
Closed 7 years ago.
I would like to ask help whether am I doing the right thing or not. You see I am trying to test myself by displaying the bit pattern of a number in the most efficient way as possible. But I'm having trouble on how to display the pattern cause I'm still learning javascript. Here's my code.
<script>
var bitPattern = function(given) {
for(var i = 1 << 31; i > 0; i = i / 2){
document.write((given & i) ? 1 : 0);
}
};
var number = prompt("Enter a number to convert: ");
bitPattern(number);
</script>

The best way to do this is:
var number = prompt("Enter a number to convert: ");
var bitPattern = parseInt(number).toString(2);
document.write(bitPattern);

Related

I'm trying to create a function that follows the Luhn's Algorithm [duplicate]

This question already has answers here:
Implementation of Luhn algorithm
(14 answers)
Closed 9 months ago.
This post was edited and submitted for review 9 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I tried to multiply each number whose index number is an even number by two, and that worked fine. Still, the problem lies here: If any of the results is greater than or equal to 10, then add up the two numbers, for example, if one of the results is 12, then add up 1 and 2, which should be equal to 3. So this is what I tried:
var num = 122345643345673;
var convNum = num.toString();
var aftertoString = convNum.split("");
for(let i = 1; i < aftertoString.length; i++){
if (i % 2 == 0) {
var multi = aftertoString[i] * 2;
if(multi > 10){
var multiStringed = multi.toString();
var aftermutliStringed = multiStringed.split("");
var first = parseInt(aftermutliStringed[2])
var multi = first + first;
}
console.log(multi);
}
}
Since any index of the "aftermultiSringed" array is not a number, I tried to convert it to a number using the "parseInt()" method, but the result is NaN, please why am I getting this.
The method parseInt usage is incorrect.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
// var first = aftermultiStringed[1].parseInt();
var first = parseInt(aftermultiStringed[1]);

Manipulating a String's content with an Integer [duplicate]

This question already has answers here:
Repeat String - Javascript [duplicate]
(30 answers)
Closed 6 years ago.
I'f you're familiar with Python, I'm sure you're aware that you can multiply a String by an Integer to get that desired amount of Strings back.
Example:
'J' * 3 --> 'JJJ'
What's the most efficient way to do this in JavaScript?
I was looking for an inline method; similar to that of Pythons behaviour
A few of my ideas:
var str = 'J',
strOld = str,
timesToExtend = 3;
for(var i = 0; i < timesToExtend; i++){
str += strOld;
}
= 'JJJ'
var str = 'J',
timesToExtend = 5,
strOld = str;
while(!timesToExtend){
str += strOld;
timesToExtend--;
}
These are just rough ideas, so don't expect them to be 100% accurate and working. I assume this MUST contain a loop; however any method without a loop will be praised!
Thanks for reading; thank you for your response in advance!
In ES6 you can use Array.prototype.fill() and then join the array:
Array(3).fill('J').join('');

for loop with chars java script [duplicate]

This question already has answers here:
How can I display letters using html table cells as colored pixels?
(2 answers)
Closed 7 years ago.
Quick question. I am trying to give out numbers with a for loop in JavaScript.
Unfortunately this is not working, if I would code in java then the solution would be replace var with char and cosole.log with println and got it, but hereā€¦ do you have a solution for that ?
for ( var i = 'a'; i < 'z'; i++) {
console.log(i);
}
for (var i = 'a'; i !== nextChar('z'); i = nextChar(i)) {
console.log(i);
}
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}

Javascript to turn 110,000 into 110K and not 0.11M [duplicate]

This question already has an answer here:
Format a javascript number with a Metric Prefix like 1.5K, 1M, 1G, etc [duplicate]
(1 answer)
Closed 7 years ago.
To start with you need...
function m(n,d){x=(''+n).length,p=Math.pow,d=p(10,d)
x-=x%3
return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}
Then calling like so...
// m( ANY NUMBER HERE or VAR LIKE I USE,HOW DECIMAL PLACES)
m(110000,2)
However instead of the above's result of 0.11M, I would like it to display 110k.
What you have there is an example of an overly optimized script, lets make it more developer friendly an readable
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+n).length;
decimalPlaces=Math.pow(10,d); //raise 10 to the number of decimal places
var modLen = numberLength - numberLength%3;
var sufix = sufixes[modLen/3];
return Math.round(rawNumber*decimalPlaces/decimalPlaces(10,modLen))/decimalPlaces+ sufix;
}
Now it's easier to work with. We can see the issue is that we need to adjust for when the string is divisible by 3, so lets fix that.
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+rawNumber).length;
decimalPlaces=Math.pow(10,decimalPlaces); //raise 10 to the number of decimal places
//THis is the change
//If the length is divisable by 3 take 3 off the length
var modLen = numberLength%3 == 0 ? numberLength - 3 - (numberLength%3) : numberLength - (numberLength%3);
console.log(modLen);
var sufix = sufixes[(modLen/3)]
console.log(sufix)
return Math.round(rawNumber*decimalPlaces/Math.pow(10,modLen))/decimalPlaces+ sufix;
}
$(document).ready(function(){
$("#result").html(metricPrefix(110000,2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>

JavaScript check if number is whole [duplicate]

This question already has answers here:
How do I check that a number is float or integer?
(52 answers)
Closed 7 years ago.
im trying to check if a number is a whole after a calculation. What I have so far prints out how many times one number gets divided by another, but when the number is not whole it dose not print anything out. Heres my code:
function round() {
var percent = document.getElementById('percent_sale').value;
var perShare = document.getElementById('singleShare').value;
var result = (percent / perShare);
if(result % 1 == 0) {
document.getElementById('results1').innerHTML = ('Number of shares:'+result);
} else {
document.getElementById(results1).innerHTML = ('number of shares must ');
}
}
The values get input buy a user, and the percent for sale is say 50 and the single share is say 2.5 this would return 20 shares.
What I need is if I put in something like 50 for sale and 3.15 single share it tells the user to make equal number of shares as it would return 15.87
Any ideas where ive gone wrong?
Convert your number into string and then check if the string contains only numbers
var num = 15;
var n = num.toString();
This will convert it into string then this
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
For further reference.Link StackOverFlow

Categories