I used random function, to generate a 4 digit number.
The generated 4 digit random number should not be in the sequence of 1111, 2222, 3333, .... The generated random number could be of any number except 1111, 2222, 3333, 4444,..
I used the below approach,
But, i could get the repeating of digits using the below code. Could somebody please help.
function repeatingDigit(n) {
let num = n.toString();
for (var i = 0; i <= num.length; i++) {
if (num.substr(i) == num.substr(++i)) {
alert('This pattern can not be used');
}
else {
return parseInt(n);
}
}
}
repeatingDigit(Math.floor(1000 + Math.random() * 9000));
Thank you.
You could just check if it's divisible by 1111:
function repeatingDigit(n) {
if (n % 1111 === 0) {
alert('This pattern can not be used');
}
return n;
}
repeatingDigit(Math.floor(1000 + Math.random() * 9000));
You can use a regular expression to test for that:
function repeatingDigit(n) {
let num = n.toString();
if (/(\d)\1{3}/.test(num)) {
alert('This pattern can not be used');
} else {
return parseInt(n);
}
}
repeatingDigit(Math.floor(1000 + Math.random() * 9000));
The regular expression /(\d)\1{3}/ tests for digits \d and checks if the following three characters are the same as the first found digit.
You can also use every() function which is inbuilt function provided by javascript to check wheather number is repeated or not after splitting number to array.
function repeatingDigit(num) {
var arr = String(num).split('');
if(arr.every(function (digit) { return digit === arr[0]}))
return 'Repeated Number!!';
else
return num;
}
console.log(repeatingDigit(Math.floor(1000 + Math.random() * 9000)))
Hope This Answer Will Help You! Happy Coding :)
Related
If the number after decimals is 0 then remove the zero after decimal else display the number as it is.
Below is the example what I am trying to achieve in vue.
100.023 => 100.023
1230.0 => 1230
This seems to do it:
let s;
// example 1
s = (100.023).toPrecision();
console.log(s === '100.023');
// example 2
s = (1230.0).toPrecision();
console.log(s === '1230');
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
function removeDecimal(num) {
if (num % 1 !== 0) {
return num;
}
return Math.trunc(num);
}
There are no significant digits in JavaScript so when you have the number 1234.0 it is 1234. If you have a string with "1243.0" convert it to a number and watch the decimal drop off.
console.log(1234.0);
console.log(1234.056);
console.log(+"1234.0");
console.log(+"1234.056");
Also You Can Use the this##
UnitCost = 340.450000000;
NewUnitCost =0;
NewUnitCost =FormatNum(UnitCost, 3);
OutPut:
NewUnitCost = 340.450
I am creating a function that returns whether the passed in number is odd Without the modulo operator. The tricky part is that it should work for NEGATIVE numbers and ZERO.
here's my codes so far:
function testodd(num) {
return (num/2)*2==num;
}
var output = testodd(17);
console.log(output); // --> true
Am I making some mistakes here? Or is there a better way to do this?
you can use Bitwise operator and get same result. does this help.
<script type="text/javascript">
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
console.log(oddOrEven(10));
</script>
For more detail about bitwise operator
Hi you can do it with bitwise AND (&) operator to check if a number is even or odd.
function testodd(num) {
if((num & 1) == 0){
return true
}
return false;
}
var output = testodd(17);
console.log(output); // --> false
var output = testodd(-16);
console.log(output); // --> true
var output = testodd(0);
console.log(output); // --> true
Try a bit-wise operation
function testodd(num) {
return num & 1; // num AND 0x1 checks for the least significant bit, indicating true or falsey
}
Remove the decimal part after division using Math.floor.
Math.floor(num / 2) * 2 === num;
For even numbers, there is no loss in decimal value. For odd numbers, decimal point value will be lost and comparison will falsy.
Here is a horribly inefficient method using recursion:
function checkOdd(num)
{
num = Math.abs(num);
if(num==0)
return false;
else if(num==1)
return true;
else
return checkOdd(num-2);
}
Of course you should never use it.
Since there's already an answer I will show you an alternative away of doing it with regex
function checkOdd(num){
console.log(/^\d*[13579]$/.test(num));
}
checkOdd(105);
Would only work with reasonably sized integers
Try
function testodd(num){
if num < 0{
var number = -num
}
int i = 1;
int product = 0;
while (product <= num)
{
product = divisor * i;
i++;
}
// return remainder
return num - (product - divisor);
}
Use this function to check if a number is odd or even, without using the modulo operator %. This should work for negative numbers and zero.
function checkOdd(num) {
// your code here
if(num<0){ //Check if number is negative
num=-num; //Convert it into positive number
}
let b=Math.floor(num/2) //Taking value for loop iteration
for(var i=1;i<=b;i++){
num=num-2; //Will check the number is odd if it subtraction end to 1 by decrementing -2 to the number
if(num==1){
return true; //return true if number is odd
}
}
return false; //return false if number is even
}
You can use isInteger method
function isEven(n){
return Number.isInteger(n / 2);
}
function odd(num) {
if (num === 0) {
return false;
}
num = Math.abs(num);
while (num >= 2) {
num = num - 2;
}
if (num === 1) {
return true;
} else {
return false;
}
}
Even number
lets take an even number say 6;
6 divided by 2 is 3;
Math.round(3) is 3;
Math.floor(3) is 3;
3===3 eveluates to true so 6 is an even number;
Odd number
lets take an odd number say 9;
9 divided by 2 is 4.5;
Math.round(4.5) is 5;
Math.floor(4.5) is 4;
5===4 evaluates to false so 9 is an odd number;
function evenChecked(num) {
if (Math.round(num / 2) === Math.floor(num / 2)) {
return `${num} is even`;
} else {
return `${num} is odd`;
}
}
console.log(evenChecked(23));
console.log(evenChecked(90));
console.log(evenChecked(56));
console.log(evenChecked(49));
goal: take a number like 54321, add the numbers together (5+4+3+2+1 = 15), then take that number (15) add the digits (1+5 = 6), so return 6;
here is my code:
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
}
}
digital_root(1632)
Can't figure out: How to get that function to repeat over and over until digits is just one number (i.e. less than 10). I have tried a variety of nested functions, but can't seem to get it right.
If possible please point me in the direction to the solution ("try a nesting in a while... or read up on..."), but don't give me the complete code solution ("Use this code chunk:...."). I've developed a bad habit of just reading and copying...
Thank you!
Try this: reference HERE
function digital_root(n) {
var singlesum = 0;
while (n >= 10 ) {
singlesum=0;
while (n > 0) {
var rem;
rem = n % 10;
singlesum = singlesum + rem;
n = parseInt(n / 10);
}
n = singlesum;
}
console.log(singlesum);
}
digital_root(1632)
You can use recursion to solve this.
Write a function makeSingleDigit, which argument will be your number.
You need a base condition with the base step, which in your case stops the recursion when received number is one-digit and returns the number.
If condition is not true, you just need to get another digit from the number by n%10 and sum it with the makeSingleDigit(Math.floor(n/10)). By this, you repeatedly sum digits of new numbers, until function receives one-digit number.
Mathematical solution just for your information: the number, which you want to find is n % 9 === 0 ? 9 : n % 9, thus it is the remainder of the division by 9 if it is not 0, otherwise it is 9.
Here is a very optimal solution to the problem:
function digital_root(n) {
return (n - 1) % 9 + 1;
}
const result = digital_root(1632);
console.log(result);
Well, not a very good solution but you can give a hit.
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
return(digits);
}
}
var num = 1632;
do{
num = digital_root(num);
}while(num>10);
I'm trying to make a decimal to hexadecimal converter without using Number.prototype.toString (this is an assignment which does not allow that function). I am attempting to use recursion to try to work it. Everything works until the else inside the main else if that makes any sense. It gives me that error when I run it for any number above 255 (i.e. any number which has more than 2 digits in hexadecimal). Does anyone know why this is the case?
var number = parseInt(prompt("Give me a number and I will turn it into hexadecimal!"));
var digit = 1;
var hexConverter = function () {
if (digit === 1) {
if (Math.floor(number / 16) === 0) {
console.log(hexDigits[number]);
} else {
digit = 16;
console.log(hexConverter(), hexDigits[number % 16]);
}
} else {
if (Math.floor(number / (digit * 16)) === 0) {
return (hexDigits[Math.floor(number / digit)]);
} else {
return (hexConverter(), hexDigits[number % (digit * 16)]);
}
digit = digit * 16;
}
};
hexConverter();
You are changing digit after making the recursive call, so it will be stuck at 16 and never get to the point where you increase it.
Move the digit = digit*16; to before the recursive call, just as you have digit = 16 in the first part.
function toHex(x) {
var res='',h;
while (x) {
res=(((h=x&15)<10)? h : String.fromCharCode(55+h)) + res;
x>>=4;
}
return res;
}
Would work quite fine.
Question to you : why only 'quite' ? :-)
Example: We have the number 1122. I would like to check that if given number contains the digit 1 more than once. In this case, it should return true.
I need the code to be flexible, it has to work with any number, like 3340, 5660, 4177 etc.
You can easily "force" JS to coerce any numeric value to a string, either by calling the toString method, or concatenating:
var someNum = 1122;
var oneCount = (someNum + '').split('1').length;
by concatenating a number to an empty string, the variable is coerced to a string, so you can use all the string methods you like (.match, .substring, .indexOf, ...).
In this example, I've chosen to split the string on each '1' char, count and use the length of the resulting array. If the the length > 2, than you know what you need to know.
var multipleOnes = ((someNum + '').split('1').length > 2);//returns a bool, true in this case
In response to your comment, to make it flexible - writing a simple function will do:
function multipleDigit(number, digit, moreThan)
{
moreThan = (moreThan || 1) + 1;//default more than 1 time, +1 for the length at the end
digit = (digit !== undefined ? digit : 1).toString();
return ((someNum + '').split(digit).length > moreThan);
}
multipleDigit(1123, 1);//returns true
multipleDigit(1123, 1, 2);//returns false
multipleDigit(223344,3);//returns 3 -> more than 1 3 in number.
Use javascript's match() method. Essentially, what you'd need to do is first convert the number to a string. Numbers don't have the RegExp methods. After that, match for the number 1 globally and count the results (match returns an array with all matched results).
var number = 1100;
console.log(number.toString().match(/1/g).length);
function find(num, tofind) {
var b = parseInt(num, 10);
var c = parseInt(tofind, 10);
var a = c.split("");
var times = 0;
for (var i = 0; i < a.length; i++) {
if (a[i] == b) {
times++;
}
}
alert(times);
}
find('2', '1122');
Convert the number to a string and iterate over it. Return true once a second digit has been found, for efficiency.
function checkDigitRepeat(number, digit) {
var i, count = 0;
i = Math.abs(number);
if(isNaN(i)) {
throw(TypeError('expected Number for number, got: ' + number));
}
number = i.toString();
i = Math.abs(digit);
if(isNaN(i)) {
throw(TypeError('expected Number for digit, got: ' + digit));
}
digit = i.toString();
if(digit > 9) {
throw(SyntaxError('expected a digit for digit, got a sequence of digits: ' + digit));
}
for(i = 0; i < number.length; i += 1) {
if(number[i] === digit) {
count += 1;
if(count >= 2) { return true; }
}
}
return false;
}
In the event that you want to check for a sequence of digits, your solution may lie in using regular expressions.
var myNum = '0011';
var isMultipleTimes = function(num) {
return !!num.toString().match(/(\d)\1/g);
}
console.log(isMultipleTimes(myNum));
JavaScript Match
Using #Aspiring Aqib's answer, I made a function that actually works properly and in the way I want.
The way it works is:
Example execution: multDig('221','2')
Split the number (first argument) to an array where each element is one digit.Output: ['2','2','1']
Run a for loop, which checks each of the array elements if they match with the digit (second argument), and increment the times variable if there is a match.Output: 2
Check inside the for loop if the match was detected already to improve performance on longer numbers like 2211111111111111
Return true if the number was found more than once, otherwise, return false.
And finally the code itself:
function multDig(number, digit){
var finalSplit = number.toString().split(''), times = 0;
for (i = 0; i < finalSplit.length; i++){
if (finalSplit[i] == digit){
times++
}
if (times > 1){
return true;
}
}
return false;
}