网易16年研发笔试题 - 小易的升级之路

问题

小易经常沉迷于网络游戏.有一次,他在玩一个打怪升级的游戏,他的角色的初始能力值为 a.在接下来的一段时间内,他将会依次遇见n个怪物,每个怪物的防御力为b1,b2,b3…bn. 如果遇到的怪物防御力bi小于等于小易的当前能力值c,那么他就能轻松打败怪物,并 且使得自己的能力值增加bi;如果bi大于c,那他也能打败怪物,但他的能力值只能增加bi 与c的最大公约数.那么问题来了,在一系列的锻炼后,小易的最终能力值为多少?


输入描述

对于每组数据,第一行是两个整数n(1≤n<100000)表示怪物的数量和a表示小易的初始能力值.
第二行n个整数,b1,b2…bn(1≤bi≤n)表示每个怪物的防御力


输出描述

对于每组数据,输出一行.每行仅包含一个整数,表示小易的最终能力值


输入样例

3 50
50 105 200
5 20
30 20 15 40 100


输出样例

110
205


Java Code

import java.util.Scanner;

public class Farm {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int num = 0;
        int ability = 0;

        while (scan.hasNext()) {
            num = scan.nextInt();
            ability = scan.nextInt();
            for (int i = 0; i < num; ++i) {
                int monster = scan.nextInt();
                if (monster <= ability)
                    ability += monster;
                else
                    ability += GCD(ability, monster);
            }
            System.out.println(ability);
        }

        scan.close();
    }

    // 辗转相除法求最大公约数
    public static int GCD(int a, int b) {
        int temp;
        while (b > 0) {
            temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}

说明

  • 本题对于了解最大公约数求法的同学来说没有难度。这里需要接收多组输入,并分别给出对应的输出结果,最开始我在while循环中使用hasNextLine()方法判断是否还有输入,结果提交代码后一直报空指针/野指针异常,排查了很久才发现应该要用hasNext()方法,可能有些同学也遇到了这个问题。我们可以对比一下JDK的API文档中这两个方法的说明:

    public boolean hasNext()

    Returns true if this scanner has another token in its input.
    This method may block while waiting for input to scan.
    The scanner does not advance past any input.

    @return true if and only if this scanner has another token
    @throws IllegalStateException if this scanner is closed
    @see java.util.Iterator

    public boolean hasNextLine()

    Returns true if there is another line in the input of this scanner.
    This method may block while waiting for input. The scanner does not advance past any input.

    @return true if and only if this scanner has another line of input
    @throws IllegalStateException if this scanner is closed

  • 辗转相除法,又名欧几里德算法,是一种非常高效的求最大公约数(GCD)的算法,它无需分解两个整数的质因子,辗转相除法的递推公式是GCD(a,b)==GCD(b,a%b),当a%b==0时,b即为所求的最大公约数。辗转相除法的效率非常高,但是在计算超大整数之间的GCD时存在缺陷,因此有人进行对其进行改进得到了Stein算法。

  • 求GCD还有一种简洁方法叫做辗转相减法,出自我国古代数学专著《九章算术》,在书中被称为“更相减损术”。

    可半者半之,不可半者,副置分母、子之数,以少减多,更相减损,求其等也。以等数约之。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值