Find the least number of coins required that can make any change from 1 to 99 cents

后端 未结 27 2198
生来不讨喜
生来不讨喜 2020-12-07 10:08

Recently I challenged my co-worker to write an algorithm to solve this problem:

Find the least number of coins required that can make any change from

27条回答
  •  天命终不由人
    2020-12-07 10:20

    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Scanner;
    
    public class LeastNumofCoins 
    {
    
    
        public int getNumofCoins(int amount)
            {
                int denominations[]={50,25,10,5,2,1};
                int numOfCoins=0;
                int index=0;
                while(amount>0)
                {
                    int coin=denominations[index];
                     if(coin==amount)
                     {
                         numOfCoins++;
                         break;
                     }
                    if(coin<=amount)
                        {
                            amount=amount-coin;
                            numOfCoins++;
                        }
                        else
                        {
                            index++;
                        }
    
                }
                return numOfCoins;
        }
        public static void main(String[] args) throws IOException 
        {
    
              Scanner scanner= new Scanner(new InputStreamReader(System.in));
              System.out.println("Enter the Amount:");
              int amoount=scanner.nextInt();
              System.out.println("Number of minimum coins required to make "+ amoount +" is "+new LeastNumofCoins().getNumofCoins(amoount));
              scanner.close();
        }
    }
    

提交回复
热议问题