Minimum Addition to Make Integer Beautiful

zeeshanali0704

ZeeshanAli-0704

Posted on November 8, 2022

Minimum Addition to Make Integer Beautiful

Minimum Addition to Make Integer Beautiful

const makeIntegerBeautiful = (n, target) => {
  // calling digit function which will give us all number in array format
  let d = digits(n);
  // checking sum of all current digits
  let s = d.reduce((a, b) => a + b);
  // this is to check what sum we have to add to make it beautiful
  let beautifier = 0;
  // index to keep 0th tenth, hundredth place in number system
  let i = 0;

  // looping till s is greater than target
  while (s > target) {
    // talking the last digit of n i.e.. 0 index from digit array
    // subtracting it from 10 to get number which we can add to make it 10
    const m = (10 - d[0]) % 10;
    // adding it to beautifier to count sum & Math.pow will give us place of number i.e.,0th tenth, hundredth place in number system
    beautifier += m * Math.pow(10, i++);
    n += m;
    // this is to remove the last 0 from number if number is suppose 470  then will make n to 47
    n = n / 10;
    d = digits(n);
    s = d.reduce((a, b) => a + b);
  }

  return beautifier;
};

const digits = (n) => {
  const digist = [];
  while (n !== 0) {
    digist.push(n % 10);
    n = Math.floor(n / 10);
  }
  return digist;
};

console.log(makeIntegerBeautiful(16, 6));

Enter fullscreen mode Exit fullscreen mode
đź’– đź’Ş đź™… đźš©
zeeshanali0704
ZeeshanAli-0704

Posted on November 8, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related