java代码中计算错误(leet代码)

问题描述 投票:0回答:1

问题:- “赫西想为他的第一辆车存钱。他每天都会把钱存入 Leetcode 银行。

他首先在第一天星期一投入 1 美元。从周二到周日,他每天都会比前一天多投入1美元。接下来的每个星期一,他都会比前一个星期一多投入 1 美元。 给定 n,返回第 n 天结束时他在 Leetcode 银行中的总金额。'

代码:-

public class Practice {
    public static int weekCalc (int a , int n){
        // a - week count 
        //n - number of days 
        int c = (n/2)*(2*a + n - 1);
        return c;
    }

    public static int total (int n ){
        int sum = 0;
        if (n<=7){
            sum +=  weekCalc(1, n); 
        } else {
            int num = n/7;
            for (int i =1 ; i<= num; i++){
                sum +=  weekCalc(i, 7);
            }
            int d = n%7;
            sum += weekCalc(num +1, d);
        }
        return sum ;

    }
    public static void main (String args[]){
       int ans = total(5);
       System.out.println(ans);
    }
}

这是 Leetcode 1716.Leetcode 银行问题。我尝试使用 AP 之和来解决它,但 weekCalc 函数似乎有错误,它没有给我正确的输出。 就像 weekCalc (1,5) 一样,输出应该是 15 但它给了我 12 。我已经多次交叉检查了代码;我知道还有其他方法可以解决这个问题,但为什么这个方法不起作用??

java logic
1个回答
0
投票

这里有一个更简单的方法:

    int totalMoney(int n) {
        int current_days=0;
        int total=0;
        int monday_deposit=0;
        int prev_deposit=0;

        while(current_days!=n){
            if(current_days%7==0){ // It is a Monday!!!
                monday_deposit+=1;
                prev_deposit=monday_deposit;
            } else{
                prev_deposit+=1;
            }
            total+=prev_deposit;
            current_days++;
        }

        return total;
    }

核心思想是按照天数维持之前的押金。我希望代码是不言自明的。

© www.soinside.com 2019 - 2024. All rights reserved.