These are the logical steps which I need to do with jquery:
x is a 2 digit number(integer) derived from an input.value();
If var x is **not** 33 or 44
Convert this 2 digit number to string;
split the string in 2 parts as number;
Add these 2 values until they reduce to single digit;
Return var x value as this value;
Else
Return var x value literally as 33 or 44 whatever is the case;
Thanks!
if (x != 33 && x != 44) {
while (x > 9) {
var parts = ('' + x).split('');
x = parseInt(parts[0]) + parseInt(parts[1]);
}
return x;
} else {
return x;
}
Works only if the input is really max 2 digits long as you say, else you'll need to add the numbers in a for loop over parts.length. E.g.:
if (x != 33 && x != 44) {
while (x > 9) {
var parts = ('' + x).split('');
for (var x = 0, i = 0; i < parts.length; i++) {
x += parseInt(parts[i]);
}
}
return x;
} else {
return x;
}
I'd try:
function process (x) {
if ((x != 33) && (x != 44)) {
while (x > 9) {
x = Math.floor (x / 10) + (x % 10);
}
}
return x;
}
I see little reason to convert it to a string when you can use arithmetic operations.
Related
I want to have a logic where if I enter an even number I want next 10 even numbers to be printed and If I enter an odd number, I want next 10 odd numbers to be printed. How should I rectify this logic inside a function. If someone can please help me rectifying the logic which was answered.
JS
function oddEven() {
var input = prompt("");
for (let x = 1; x <= 10; x++) {
console.log(input + x * 2);
}
}
oddEven()
This should work for any number
const input = 2
for (let x = 1; x <= 10; x += 1) {
console.log(input + x * 2)
}
i hope this help
function printTen(input){
let list = []
let number = input
while(list.length <= 10){
number++
if(input % 2 === 0 && number % 2 === 0){
console.log(number + " is even");
list.push(number)
}else if(input % 2 !== 0 && number % 2 !== 0) {
console.log(number + " is odd");
list.push(number)
}
}
}
printTen(9)
let inputval = 2;
for (let x = 1; x <= 10; x++) {
console.log(inputval + x * 2)
}
I'm busy with a udacity excercise and the following question:
A while loop that:
Loop through the numbers 1 to 20
If the number is divisible by 3, print "Julia"
If the number is divisible by 5, print "James"
If the number is divisible by 3 and 5, print "JuliaJames"
If the number is not divisible by 3 or 5, print the number
I keep submitting the answer but it tells me that my while loop condition is incorrect, Is there anything im doing wrong?
var x = 1;
while (x <= 20) {
if (x/3 === 0) {
console.log("julia" );
} // check divisibility
else if (x/5 === 0) {
console.log("james");
}
else if (x/5 === 0 && x/3 === 0 ) {
console.log("juiliajames");
} // print Julia, James, or JuliaJames
else {
console.log(x);
}
x= x + 1;// increment x
}
You need to use Modulus (%) instead of divide (/). And make x % 5 === 0 && x % 3 === 0 as your first condition.
Change your code like following.
var x = 1;
while (x <= 20) {
if (x % 5 === 0 && x % 3 === 0) {
console.log("juiliajames");
} // print Julia, James, or JuliaJames
else if (x % 3 === 0) {
console.log("julia");
} // check divisibility
else if (x % 5 === 0) {
console.log("james");
} else {
console.log(x);
}
x = x + 1; // increment x
}
var x = 1;
while (x <= 20) {
if(x%3 === 0 && x%5 === 0 ){
console.log("juiliajames" );
} // check divisibility
else if(x%3 === 0){
console.log("juilia");
}
else if (x%5 === 0){
console.log("james");
} // print Julia, James, or JuliaJames
else{
console.log(x);
}
x= x + 1;// increment x
}
If you want to check divisibility, you should use the % operator instead of / operator.
Check x divisible by 5 AND 3 at the begining or it will never been done because if it is divisible by 3 your loop won't go to the else if statment.
To check divisibility use modulo (x/3 === 0 only for x = 0)
var x = 1;
while (x <= 20) {
if(x%5 === 0 && x%3 === 0){
console.log("juiliajames" );
}
else if(x%5 === 0){
console.log("james");
}
else if (x%3 === 0 ){
console.log("juilia");
}
else{
console.log(x);
}
x= x + 1;// increment x
}
My approach works by setting bitwise flags on an integer. If it's divisible by three (value % 3 === 0, where % is 'modulo' which gives an integer remainder from division) The first bit is set and if it's divisible by five the second bit is set. That gives a result that could have three binary values 01, 10 or 11, or in decimal 1, 2 & 3 (The three comes about when both bits are set).
var DIVISABLE_BY_THREE = 1;
var DIVISABLE_BY_FIVE = 2;
var DIVISABLE_BY_THREE_AND_FIVE = 3;
var value = 0;
while(value++ < 20) {
var modulo_3 = (value % 3 === 0) | 0;
var modulo_5 = ((value % 5 === 0) | 0) << 1;
switch(modulo_3 | modulo_5) {
case DIVISABLE_BY_THREE:
console.log("Julia");
break;
case DIVISABLE_BY_FIVE:
console.log("James");
break;
case DIVISABLE_BY_THREE_AND_FIVE:
console.log("JuliaJames");
break;
default:
console.log(value);
break;
}
}
var x = 1;
while (x <= 20) {
var name ="";
if (x % 3 == 0) {
name = name + "julia";
}
if (x % 5 == 0) {
name = name + "james";
}
if(name.length > 0)
console.log(name);
else
console.log(x);
x++;
}
I'm sending the number/string 0.001 to a the function below:
SignificantFigures = 4;
function LimitNumberOfDigits(num) {
var tempStr = "";
if (isNaN(num))
return "\xD8";
else{
if (parseFloat(num) === 0 || (num.toString().indexOf('.') === -1 && parseInt(num) < 9999) || num.toString().length <= 4) {
return num;
}
tempStr = parseFloat(num).toPrecision(SignificantFigures);
if (tempStr.indexOf("e") > -1) {
var startE = tempStr.indexOf("e");
var endE = 0;
for (var i = startE +2 ; i < tempStr.length; i++ ) { // + to ignore e and sign (+ or - )
if(parseInt(tempStr[i], 10) > 0) {
endE = i;
}else {
break;
}
}
if (startE + 2 === endE) {
var pow = tempStr[endE];
} else {
var pow = tempStr.substring(startE +2 ,endE);
}
return tempStr.substring(0,startE) + "*10<sup>"+ pow +"</sup>";
}else {
return parseFloat(num).toPrecision(SignificantFigures);
}
}
}
When im sending 0.2 or even 0.11 im getting like 0.2000 and 0.1100.
The issue here is the toPrecision acts like ToFixed.
Ideas?
EDIT
What i want? simple as that, if a numbers needs to be changed e.g 0.012312312041 it should be 0.0123 , numbers like 0.12 or 28 should stay the same.
Is there a simple way (hoping for a small function, not a library) to add or subtract from a 64bit integer in JavaScript?
Example 64bit int: 291270990346989568
Background: I am working with the Twitter API which has 64bit tweet ID's. I'd like to add or subtract one from those IDs to manipulate what results I get back from Twitter.
The following code does what you've described.
Splitting, adding or subtracting, then re-joining...
This code has both increment and decrement functions, and a test function with some edge cases. When splitting number strings and doing math on them, you need to consider what happens to "leading zeroes", so there's a padding function for that.
Thanks, Justin, for providing a JSFiddle with this solution.
/*
* Prepend zeros to expand a given string to given length
*
* #var {String} numStr Number
* #var {Number} len Length to pad out to
*
* #returns {String}
*/
function pad0 (numStr,len) {
while (numStr.length < len) {
numStr = "0" + numStr;
}
return numStr
}
/*
* Decrement the given (64 bit) integer.
*
* #var {String} int64 Postive non-zero integer, as a string
*
* #returns {String}
*/
function decrInt64 (int64) {
var result = "";
var midpt = Math.floor(int64.length/2);
var upper = int64.substring(0,midpt);
var lower = int64.substring(midpt);
var upperVal = new Number(upper);
var lowerVal = new Number(lower);
if (lowerVal == 0) {
if (upperVal == 0) {
// We don't support negative numbers
result = "*ERROR*"
}
else {
// borrow 1
result = pad0((--upperVal).toString(),upper.length) +
(new Number("1"+lower) - 1).toString();
}
}
else {
var newLower = (lowerVal - 1).toString();
result = upper + pad0(newLower,lower.length);
}
alert(result);
}
/*
* Increment the given (64 bit) integer.
*
* #var {String} int64 Postive, as a string
*
* #returns {String}
*/
function incrInt64 (int64) {
var result = "";
var midpt = Math.floor(int64.length/2);
var upper = int64.substring(0,midpt);
var lower = int64.substring(midpt);
var upperVal = new Number(upper);
var lowerVal = new Number(lower);
var newLower = (++lowerVal).toString();
// Did we overflow?
if (lower.length < newLower.length) {
// Yes, carry the 1
result = (++upperVal).toString() + newLower.substring(1);
}
else {
result = upper + pad0(newLower,lower.length);
}
alert(result);
}
// Test function
window.displaymessage= function ()
{
decrInt64("291270990046989568");
incrInt64("291270990046989568");
decrInt64("000000000000000000");
incrInt64("000000000000000000");
decrInt64("000000001000000000");
incrInt64("000000001000000000");
decrInt64("099999999999999999");
incrInt64("099999999999999999");
decrInt64("999999999999999999");
incrInt64("999999999999999999");
}
Addition of integer-formatted strings (base 10) of indefinite lengths can be done by splitting the string into segments of 9 characters, calculating + or - for that and then moving to the preceding 9 characters. This is because the largest 9 character number, 999999999 is 32-bit safe (as is 1999999999, which I used in subtraction).
The following code has 3 functions and the word integer is assumed to mean an integer-formatted string.
addAsString, takes two non-negative integers x and y, returns x + y
subtractAsString, takes two non-negative integers x and y, |x| >= |y|, returns x - y
addORsub, takes any two integers x and y, returning x + y
I've tried to explain what is happening via comments in the code
// Indefinate length addition
function addAsString(x, y) { // x, y strings
var s = '';
if (y.length > x.length) { // always have x longer
s = x;
x = y;
y = s;
}
s = (parseInt(x.slice(-9),10) + parseInt(y.slice(-9),10)).toString(); // add last 9 digits
x = x.slice(0,-9); // cut off last 9 digits
y = y.slice(0,-9);
if (s.length > 9) { // if >= 10, add in the 1
if (x === '') return s; // special case (e.g. 9+9=18)
x = addAsString(x, '1');
s = s.slice(1);
} else if (x.length) { // if more recursions to go
while (s.length < 9) { // make sure to pad with 0s
s = '0' + s;
}
}
if (y === '') return x + s; // if no more chars then done, return
return addAsString(x, y) + s; // else recurse, next digit
}
// Indefinate length subtraction (x - y, |x| >= |y|)
function subtractAsString(x, y) {
var s;
s = (parseInt('1'+x.slice(-9),10) - parseInt(y.slice(-9),10)).toString(); // subtract last 9 digits
x = x.slice(0,-9); // cut off last 9 digits
y = y.slice(0,-9);
if (s.length === 10 || x === '') { // didn't need to go mod 1000000000
s = s.slice(1);
} else { // went mod 1000000000, inc y
if (y.length) { // only add if makes sense
y = addAsString(y, '1');
} else { // else set
y = '1';
}
if (x.length) {
while (s.length < 9) { // pad s
s = '0' + s;
}
}
}
if (y === '') { // finished
s = (x + s).replace(/^0+/,''); // dont return all 0s
return s;
}
return subtractAsString(x, y) + s;
}
// Indefinate length addition or subtraction (via above)
function addORsub(x, y) {
var s = '';
x = x.replace(/^(-)?0+/,'$1').replace(/^-?$/,'0'); // -000001 = -1
y = y.replace(/^(-)?0+/,'$1').replace(/^-?$/,'0'); // -000000 = 0
if (x[0] === '-') { // x negative
if (y[0] === '-') { // if y negative too
return '-' + addAsString(x.slice(1), y.slice(1)); // return -(|x|+|y|)
}
return addORsub(y, x); // else swap
}
if (y[0] === '-') { // x positive, y negative
s = y.slice(1);
if (s.length < x.length || (s.length === x.length && s < x)) return subtractAsString(x, s) || '0'; // if |x|>|y|, return x-y
if (s === x) return '0'; // equal then 0
s = subtractAsString(s, x); // else |x|<|y|
s = (s && '-' + s) || '0';
return s; // return -(|y|-x)
}
return addAsString(x, y); // x, y positive, return x+y
}
Example usage (fiddle)
var i = addORsub('291270990346989568', '1'); // add
i === '291270990346989569';
i = addORsub('291270990346989568', '-1'); // subtract
i === '291270990346989567';
I have a number assigned to a variable, like that:
var myVar = 1234;
Now I want to get the second digit (2 in this case) from that number without converting it to a string first. Is that possible?
So you want to get the second digit from the decimal writing of a number.
The simplest and most logical solution is to convert it to a string :
var digit = (''+myVar)[1];
or
var digit = myVar.toString()[1];
If you don't want to do it the easy way, or if you want a more efficient solution, you can do that :
var l = Math.pow(10, Math.floor(Math.log(myVar)/Math.log(10))-1);
var b = Math.floor(myVar/l);
var digit = b-Math.floor(b/10)*10;
Demonstration
For people interested in performances, I made a jsperf. For random numbers using the log as I do is by far the fastest solution.
1st digit of number from right → number % 10 = Math.floor((number / 1) % 10)
1234 % 10; // 4
Math.floor((1234 / 1) % 10); // 4
2nd digit of number from right → Math.floor((number / 10) % 10)
Math.floor((1234 / 10) % 10); // 3
3rd digit of number from right → Math.floor((number / 100) % 10)
Math.floor((1234 / 100) % 10); // 2
nth digit of number from right → Math.floor((number / 10^n-1) % 10)
function getDigit(number, n) {
return Math.floor((number / Math.pow(10, n - 1)) % 10);
}
number of digits in a number → Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1 Credit to: https://stackoverflow.com/a/28203456/6917157
function getDigitCount(number) {
return Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1;
}
nth digit of number from left or right
function getDigit(number, n, fromLeft) {
const location = fromLeft ? getDigitCount(number) + 1 - n : n;
return Math.floor((number / Math.pow(10, location - 1)) % 10);
}
Get rid of the trailing digits by dividing the number with 10 till the number is less than 100, in a loop. Then perform a modulo with 10 to get the second digit.
if (x > 9) {
while (x > 99) {
x = (x / 10) | 0; // Use bitwise '|' operator to force integer result.
}
secondDigit = x % 10;
}
else {
// Handle the cases where x has only one digit.
}
A "number" is one thing.
The representation of that number (e.g. the base-10 string "1234") is another thing.
If you want a particular digit in a decimal string ... then your best bet is to get it from a string :)
Q: You're aware that there are pitfalls with integer arithmetic in Javascript, correct?
Q: Why is it so important to not use a string? Is this a homework assignment? An interview question?
You know, I get that the question asks for how to do it without a number, but the title "JavaScript: Get the second digit from a number?" means a lot of people will find this answer when looking for a way to get a specific digit, period.
I'm not bashing the original question asker, I'm sure he/she had their reasons, but from a search practicality standpoint I think it's worth adding an answer here that does convert the number to a string and back because, if nothing else, it's a much more terse and easy to understand way of going about it.
let digit = Number((n).toString().split('').slice(1,1))
// e.g.
let digit = Number((1234).toString().split('').slice(1,1)) // outputs 2
Getting the digit without the string conversion is great, but when you're trying to write clear and concise code that other people and future you can look at really quick and fully understand, I think a quick string conversion one liner is a better way of doing it.
function getNthDigit(val, n){
//Remove all digits larger than nth
var modVal = val % Math.pow(10,n);
//Remove all digits less than nth
return Math.floor(modVal / Math.pow(10,n-1));
}
// tests
[
0,
1,
123,
123456789,
0.1,
0.001
].map(v =>
console.log([
getNthDigit(v, 1),
getNthDigit(v, 2),
getNthDigit(v, 3)
]
)
);
This is how I would do with recursion
function getDigits(n, arr=[]) {
arr.push(n % 10)
if (n < 10) {
return arr.reverse()
}
return getDigits(Math.floor(n/10),arr)
}
const arr = getDigits(myVar)
console.log(arr[2])
I don’t know why you need this logic, but following logic will get you the second number
<script type="text/javascript">
var myVal = 58445456;
var var1 = new Number(myVal.toPrecision(1));
var var2 = new Number(myVal.toPrecision(2));
var rem;
rem = var1 - var2;
var multi = 0.1;
var oldvalue;
while (rem > 10) {
oldvalue = rem;
rem = rem * multi;
rem = rem.toFixed();
}
alert(10-rem);
</script>
function getDigit(number, indexFromRight) {
var maxNumber = 9
for (var i = 0; i < indexFromRight - 2; i++) {
maxNumber = maxNumber * 10 + 9
}
if (number > maxNumber) {
number = number / Math.pow(10, indexFromRight - 1) | 0
return number % 10
} else
return 0
}
Just a simple idea to get back any charter from a number as a string or int:
const myVar = 1234;
String(myVar).charAt(1)
//"2"
parseInt(String(myVar).charAt(1))
//2
you can use this function
index = 0 will give you the first digit from the right (the ones)
index = 1 will give you the second digit from the right (the tens)
and so on
const getDigit = (num, index) => {
if(index === 0) {
return num % 10;
}
let result = undefined;
for(let i = 1; i <= index; i++) {
num -= num % 10;
num /= 10;
result = num % 10;
}
return result;
}
for Example:
getDigit(125, 0) // returns 5
gitDigit(125, 1) // returns 2
gitDigit(125, 2) // returns 1
gitDigit(125, 3) // returns 0
function left(num) {
let newarr = [];
let numstring = num.split('[a-z]').join();
//return numstring;
const regex = /[0-9]/g;
const found = numstring.match(regex);
// return found;
for(i=0; i<found.length; i++){
return found[i];
}
}
//}
console.log(left("TrAdE2W1n95!"))
function getNthDigit(n, number){
return ((number % Math.pow(10,n)) - (number % Math.pow(10,n-1))) / Math.pow(10,n-1);
}
Explanation (Number: 987654321, n: 5):
a = (number % Math.pow(10,n)) - Remove digits above => 54321
b = (number % Math.pow(10,n-1)) - Extract digits below => 4321
a - b => 50000
(a - b) / 10^(5-1) = (a - b) / 10000 => 5
var newVar = myVar;
while (newVar > 100) {
newVar /= 10;
}
if (newVar > 0 && newVar < 10) {
newVar = newVar;
}
else if (newVar >= 10 && newVar < 20) {
newVar -= 10;
}
else if (newVar >= 20 && newVar < 30) {
newVar -= 20;
}
else if (newVar >= 30 && newVar < 40) {
newVar -= 30;
}
else if (newVar >= 40 && newVar < 50) {
newVar -= 40;
}
else if (newVar >= 50 && newVar < 60) {
newVar -= 50;
}
else if (newVar >= 60 && newVar < 70) {
newVar -= 60;
}
else if (newVar >= 70 && newVar < 80) {
newVar -= 70;
}
else if (newVar >= 80 && newVar < 90) {
newVar -= 80;
}
else if (newVar >= 90 && newVar < 100) {
newVar -= 90;
}
else {
newVar = 0;
}
var secondDigit = Math.floor(newVar);
That's how I'd do it :)
And here's a JSFiddle showing it works :) http://jsfiddle.net/Cuytd/
This is also assuming that your original number is always greater than 9... If it's not always greater than 9 then I guess you wouldn't be asking this question ;)