How to create a palindrome number from a random positive integer using a centred number palindrome?
When int S=244; return 424
When int S=12231; return 12321
When int S=2233; return 232 //drop 3 to make palindrome number
When int S=123432; return 23432 //drop 1 to make palindrome number
When int S=0000; return 0
//starting and ending with 0 is not a proper palindrome number in this code. e.g. 010, 02320 is not a palindrome number
I was thinking about making an array of the random positive integer then store the palindrome number in another array and finally return the palindrome integer
function solution(int S){ //S=1144 -> 141, so I need to drop 4...
const num=S;
const array=Array.from(String(num), Number); //array=[1,1,4,4]
const palinArray=[];
var palinNum=0;
//if num is already palindrome number
cost rev=array.reverse(); //rev=[4,4,1,1]
if(array===rev){
palinNum=Number(array.join(''));
return plainNum;
}
//if num is not palindrome, check if num can transform to a palindrome
for(var i=0;i<array.length-1;i++){
for(var k=i;k<array.length;k++){
//I thought if switching array[i] integer to the array[i+1] interger makes entire number palindrome, switch it and move i+2 for next loop but makes no sense.
}
}//end for loop
//console.log(palinNum);
}
So I think I still did not fully understand but I want to return the palindrome number of this solution function.
Related
I want to create a function that returns true if a number has consecutive digits or not,
example:
if the input is 11, it will return true
if the input is 21 it will return false
if the input is 323 it will return false because even though we have 3 repeated, they are not consecutive
My solution right now is to transform the number into an array and loop through the number one by one, if the next number is equal to the current number then we just return true. But this has a complexity time of O(n) and I was wondering if anyone can come with a better solution.
Thank you
There is an arguably better solution where you don't need to convert the number into a string or array of numbers/character. It works as follows:
Initialize a variable curr to -1.
Run a loop while num > 0 and do the following:
next_curr = num % 10
if next_curr == curr: return true
curr = next_curr
num = num / 10 (integer division)
If the loop completes, return false.
This is a one pass O(log n) time complexity algorithm where n is the input number. The space complexity is O(1)
Note that while your algorithm was also O(log n) time complexity, it did 2 passes, and had a space complexity of O(log n) too.
I haven't written JS for some time now, but here's a possible implementation of the above algorithm in JS:
function sameAdjacentDigits(num) {
// to deal with negative numbers and
// avoid potential problems when using Math.floor later
num = Math.abs(num)
let curr = -1
while (num > 0) {
const nextCurr = num % 10
if (nextCurr == curr) return true
curr = nextCurr
num = Math.floor(num / 10)
}
return false
}
Use some regex, and then check what was found via the matcher
numbers_match = /(00|11|22|33|44|55|66|77|88|99)/;
numbers_match.match("11")
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
Easiest way to execute this is by using regex. Not sure what would be effectiveness of algorithm, but solution could be
/(\d)\1/
Inspired from #Tschallacka's answer:
let numbers = [11,21,323];
let result = numbers.map(n=>{
let test = n.toString().match(/(00|11|22|33|44|55|66|77|88|99)/);
return test != null;
})
console.log(result);
I need a function to calculate the number of possible addition equations for a given sum n.
The operands must always be in descending order, cannot be equal, and must be greater than 0.
So, 5+4 is valid but 4+5 5+5 3+3+3 or 9+0 are not. Only integers are used.
For instance:
n = 2. Result is 0
n = 3. Result is 1. 2+1
n = 5. Result is 2. 4+1 and 3+2
n = 10. Result is 8. 9+1, 8+2, 7+3, 6+4, 7+2+1, 6+3+1, 5+4+1, 5+3+2
Just divide the number by 2 and floor the result:
function calc(num){
return Math.floor(num/2);
}
console.log(calc(5)) //4+1, 2+3
console.log(calc(6)) //1+5, 2+4, 3+3
console.log(calc(7)) //1+6, 2+5, 3+4
This question already has answers here:
Check Number prime in JavaScript
(47 answers)
Closed 2 years ago.
I have written the below code to check if a number is prime, and it works correctly. But to my amazement when it pass 25 as a value, it returns "true" instead of "false" because 25 is not a prime number.
So I decided to share. Please, what I am doing wrong here?
function isPrime(number) {
return number % 2 !== 0 && number % 3 !== 0 ? true : false;
}
isPrime(4) returns false;
isPrime(23) returns true;
isPrime(25) returns true;
"(Here is where I got alarmed. 25 Should return false too)
Your condition is very minimal. What if the number is not divisible by 2 or 3 but divisible by 5 or 7? Besides how come isPrime(23) returns false is okay? 23 is a prime as well it should return true. What you need to do is iterate through all the number from n-1 to 2(here n is the number you are checking) and check if any of the number divides n without a remainder. You can do the following,
function isPrime(number) {
let isPrimeNum = true;
for(let i = number-1; i>=2; i--) {
if(number%i === 0) isPrimeNum = false;
}
return isPrimeNum;
}
console.log(isPrime(23));
console.log(isPrime(25));
There is a lot of way you can optimize the above solution. I kept it as a challenge for you to find out and do by yourself. You can start from here.
Your code only checks if the input is divisible by 2 or 3. However, a prime number (by definition) is a number that's only divisible by 1 and itself.
Therefore, you have to check every number less than or equal to sqrt(n). (It's enough to scan this area, as if there's a divisor greater than that, it must have a pair that falls in that range.
The loop iterates upwards, so it can early-return, if the number is divisible by a small prime.
function isPrime(number){
if(number <= 1 || number !== Math.floor(number))
return false
const sqrtNumber = Math.sqrt(number)
for(let n = 2; n <= sqrtNumber; n++)
if(!(number % n))
return false
return true
}
console.log(isPrime(-42)) //false
console.log(isPrime(1)) //false
console.log(isPrime(3.14)) //false
console.log(isPrime(4)) //false
console.log(isPrime(23)) //true
console.log(isPrime(25)) //false
I need to create a function that takes a number and returns palindrome of this number, by summing its reverse number. For example 312 + 213 = 525. But what's more important, I must use recursion in this situation.
And, for example, number 96 needs like 4 iterations to become 4884.
The strategy is already explained in other comments. Here is a sample recursive JS-implementation that accomplishes your goal:
// Keeps recursively addding the reverse number until a palindrome
// number is obtained
function findPalindrome(num) {
numStr = num.toString();
revNumStr = numStr.split("").reverse().join("");
if (numStr === revNumStr) { // True if palindrome
return num;
} else { // Recursive part
return findPalindrome(num + parseInt(revNumStr))
}
}
console.log(findPalindrome(312));
console.log(findPalindrome(213));
console.log(findPalindrome(96));
You could
get number
convert number to string
get an array of digits
reverse the array
join the array
convert to number
add to original number
convert sum to string
iterate string and check if the value from the beginning is equal to the one at the end
if true return with sum
if false call function again with sum <-- This is the recursion part.
This may seem obvious, but what is exactly is an extra perfect number? I need to write an algorithm to find extra perfect for a given n, from 1 thru n. Unfortunately, I can't seem to wrap my mind around the question's wording. These are the examples given:
extraPerfect(3) ==> return {1,3}
extraPerfect(7) ==> return {1,3,5,7}
Task:
Given a positive integer N, return the extra perfect numbers in range from 1 to N.
A number is called Extra Perfect Number if it has the same first and last bits (set bits).
Notes:
Only positive integers will be passed.
The returned vector/list should contain the extra perfect numbers in
ascending order (from lowest to highest).
Example #1
extraPerfect(3) ==> return {1,3}
Explanation:
(1)10 = (1)2
First and last bits as set bits.
(3)10 = (11)2
First and last bits as set bits.
Example #2
extraPerfect(7) ==> return {1,3,5,7}
Explanation:
(5)10 = (101)2
First and last bits as set bits.
(7)10 = (111)2
First and last bits as set bits.
It seems to me that an extra perfect number is simply an odd number as, in base 2, it will always start and end with a 1, whereas an even number will always start with a 1 but end with a 0.
Ah now I see I was wrong because I thought it is all about palindroms. However I hope it can be still helpful. That's the code for palindroms in section between 1 to prompt's value.
var exns = (function(){
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
function isEXN(num){
var con = dec2bin(num); // 11011 = 3 + 24 = 27
var accurate = Math.ceil(con.length/2); // 5/2 = 3
var lenmin = con.length-1;
for(var i = 0; i < accurate; i++){
if(con.charAt(i) !== con.charAt(lenmin-i))
return false;
}
return true;
}
var max = parseInt(prompt("Numbers from 1 to ...?"));
var exns = [];
if(!isNaN(max)){
for(var i = 1; i<=max; i++){
if(isEXN(i))
exns.push(i);
}
}
return exns;
})();
Exns should contain array with values.
It looks like extraPerfect should return a list of all numbers less than the argument which have the same first and last digit after converting the decimal argument to binary.
For example:
Decimal - Binary
1 - 1
2 - 10
3 - 11
4 - 100
5 - 101
6 - 110
7 - 111
You'll notice the bold values have the same first and last binary digits.
Some pseudo-code might look like:
function extraPerfect( n ){
var perfects = [];
for(i=0; i<n; i++){
var binary = toBinary(i);
if(binary[0] === binary[binary.length]){
perfects.push(i);
}
}
return perfects;
}
You could pull an algorithm form the pseudo-code.
A Perfect Number is equal to the sum of its positive divisors.
function perfect(num){
for(var i=1,n=0; i<num; i++){
if(num % i === 0){
n += i;
}
}
return n === num;
}
console.log(perfect(6));
console.log(perfect(7));
console.log(perfect(28));
console.log(perfect(8127));
console.log(perfect(8128));