Interview Questions- Part-6

Pallindrom of a number

				
					// Pallindrome 1
let number = 12321;
//let number = 123321;
let x = number.toString();
let isPallindrome = true;
for (let i = 0; i < x.length / 2; i++) {
  if (x[i] !== x[x.length - 1 - i]) {
    isPallindrome = false;
  }
}
if (isPallindrome) {
  console.log("is pallindrome");
} else {
  console.log("is not pallindrome");
}
				
			
				
					// Pallindrome 2
let number = 123321;
//let number = 12321;
let original = number;
let revnum = 0;
while (number > 0) {
  let rem = number % 10;
  number = Math.floor(number / 10);
  revnum = revnum * 10 + rem;
}
if (revnum === original) {
  console.log("is pallindrome");
} else {
  console.log("is not pallindrome");
}
				
			
				
					// Pallindrome 3
let number = 123321;
//let number = 12321;
let length = number.toString().length;
let firstHalfNumber = number.toString().substring(0, length / 2);
let i = 1;
let lastHalfRevnum = 0;
while (i <= length / 2) {
  let rem = number % 10;
  number = Math.floor(number / 10);
  lastHalfRevnum = lastHalfRevnum * 10 + rem;
  i++;
}
if (firstHalfNumber === lastHalfRevnum.toString()) {
  console.log("is pallindrome");
} else {
  console.log("is not pallindrome");
}

				
			

Sum of age of all family members

				
					const familyTree = [
  {
    name: "Anurag",
    age: 82,
    children: [
      {
        name: "Rahul",
        age: 53,
        children: [
          {
            name: "Vinay",
            age: 32,
          },
          {
            name: "Priya",
            age: 28,
            children: [
              {
                name: "Srinivas",
                age: 5,
              },
            ],
          },
        ],
      },
      {
        name: "Roshan",
        age: 50,
      },
    ],
  },
  {
    name: "Abhishek",
    age: 50,
    children: [],
  },
];

//sum of all age --> 82 + 53 + 32 + 28 + 5 + 50 + 50 =300

let sum = 0;
const calculateSumOfAge = (family) => {
  if (Array.isArray(family)) {
    family.forEach((i) => {
      sum += i.age;
      if (i.children) {
        calculateSumOfAge(i.children);
      }
    });
  }
};

calculateSumOfAge(familyTree);
console.log(sum);

//output:300
				
			

Merge and Sort Number Array

				
					//Merge and sort
const x = [1, 5, 2, 5, 8, 3];
const y = [6, 1, 2, 9, 4, 6, 3];
let final = [...x, ...y].sort((a, b) => a - b);
console.log(final);
//[1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 8, 9]

				
			

Length of Number without converting to string

				
					//calculate the length of number without using .toString()
let number = 12345;
let length = 0;
while (number !== 0) {
  number = Math.floor(number / 10);
  length++;
}
console.log(length);

				
			

Leave a Comment