基本算法思想-穷举算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xj80231314/article/details/86212612


package com.xj.www.algo;
import java.util.Scanner;
/**
 * 穷举算法
 * @author xiongjing
 *
 */
public class AlgorithmTest {
      // chichen鸡的个数,rabbit兔的个数
      static int chichen, rabbit;
      // 算法具体实现
      public static int qiongJu(int head, int foot) {
            int re, i, j;
            re = 0;
            for (i = 0; i <= head; i++) {
                  j = head - i;
                  // 鸡的脚+兔的脚=总数量
                  if (i * 2 + j * 4 == foot) {
                        re = 1;
                        chichen = i;
                        rabbit = j;
                  }
            }
            return re;
      }
      // 程序主入口
      public static void main(String[] args) {
            int re, head, foot;
            System.out.println("穷举算法求解鸡兔同笼问题:");
            System.out.println("请输入头数:");
            @SuppressWarnings("resource")
            Scanner sc = new Scanner(System.in);
            head = sc.nextInt();
            System.out.println("请输入脚数:");
            foot = sc.nextInt();
            re = qiongJu(head, foot);
            if (re == 1) {
                  System.out.println("鸡有" + chichen + "只,兔有" + rabbit + "只");
            } else {
                  System.out.println("无法求解");
            }
      }
}

猜你喜欢

转载自blog.csdn.net/xj80231314/article/details/86212612