Question:
Write a function repdigit that determines whether a two-digit decimal is a repdigit or not. If the decimal is a repdigit, 'Repdigit!' should be returned, otherwise 'No Repdigit!'.
Example: repdigit(22) should return 'Repdigit!' and repdigit(23) should return 'No Repdigit!'.
Answer:
function repdigit (n) {
if (Number.parseInt(n/10) === (n/11)) {
return 'Repdigit!';
}
return 'No Repdigit!';
};
or
function repdigit(n) {
let ones = n % 10;
let tens = Math.floor(n / 10);
if (ones === tens) {
return 'Repdigit!';
}
return 'No Repdigit!';
};
> in the first example we have used the parseInt function to convert the result of n/10 into an integer
>>> then once it is converted to an integer we check its equality with the result of n/11
>>> if both the results are equal then we are returned the Repdigit output
>>> or else we are returned the No Repdigit output
> in the second example we declare a variable 'ones'
>>> we initialize it with a value
>>> like this n % 10; we use the modulo operator
>>> we get the digit in the units place when we use the modulo operator
>>> for eg 58 % 10 = 8; 8 is the remainder when we divide 58 by 10
>>> we then create another variable 'tens'
>>> we initialize it with a value
>>> like this Math.floor(n/10)
>>> we use the Math.floor in order to round down the value of n/10 to the nearest integer
>>> for eg (20.56589 / 10) = 2.056589 >>>> check in console
>>> Math.floor(2.056589) = 2 >>>> check in console
>>> we use the if / else statement to execute the code
>>> if the digits in the ones place is strictly equal to the digits in the tens place we shall get Repdigit
>>> else we get No Repdigit
No comments:
Post a Comment