skip to Main Content

I have number like 230.
And 50 is always the limit.
I want to get the following data:

[50,50,50,50,30]

I should get four 50’s and its exist number that is less than 50.

example 2.

Number = 400

I should get
[50,50,50,50,50,50,50,50]

example 3:

Number = 110

I should get

[50,50,10]

3

Answers


  1. Javascript

    function get50s(num){
      let res = [];
      while(num >= 50) {
        res.push(50);
        num -= 50;
      }
      if(num > 0) res.push(num);
      return res;
    }
    
    Login or Signup to reply.
  2. getResult(420, 50) = [50, 50, 50, 50, 50, 50, 50, 50, 20]
    
    getResult(51, 50) = [50, 1]
    
    getResult(12, 50) = [12]
    

    This is a basic way of doing it using % which is the modular operator.

    console.log(getResult(420, 50));
    
    
    function getResult(input, num) {
      if (input <= num) return [input];
    
      arr = [];
    
      for (let i = 0; i < Math.floor(input / num); i++) {
        arr.push(num);
      }
    
      let remainder = input % num;
    
      if (remainder > 0) {
        arr.push(input % num);
      }
    
      return arr;
    }
    
    Login or Signup to reply.
  3. `function fifties(num) {
        let ans = [];
        while (num > 0) {
            if (num >= 50) {
            num -= 50;
            ans.push(50);
           } else {
              ans.push(num);
              break;
             }
       }
       return ans;
    }
    console.log(fifties(340));
    

    $ node fifties.js
    [
    50, 50, 50, 50,
    50, 50, 40
    ]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search