Google 编码挑战未检测到 int

Google coding challenge not detecting int

这个程序的要点是获取一个像“1256”这样的长变量,然后将它们逐位相加,直到剩下一位整数。所以 1 + 2 + 5 + 6 = 14, 1 + 4 = 5, return 5.

当我尝试验证它时,出现错误:

public static method answer with parameters (int) not found in com.google.challenges.Answer

有人可以帮我理解这个错误的含义以及我该如何解决吗?

package​ ​com.google.challenges;​ ​

public​ ​class​ ​Answer​ ​{​ ​​ ​​ ​
​ ​​ ​​ ​​ ​public​ ​static​ ​int​ ​answer(long​ ​x)​ ​{​ ​

​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​long​ ​placeholder​ ​=​ ​0,​ ​sum​ ​=​ ​0;
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​for(int​ ​i​ ​=​ ​1;​ ​x​ ​>​ ​0​ ​&&​ ​sum​ ​<​ ​10;​ ​i++){
            // if x = 1256 then placeholder = 1256 % 10 = 6
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​placeholder​ ​=​ ​(long)(x​ ​%​ ​Math.pow(10,i));
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ //1256 - 6 = 1250
            ​x​ ​-=​ ​placeholder;
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​sum​ ​+=​ ​placeholder​ ​/​ ​(long)(Math.pow(10,​ ​i​ ​-​ ​1));
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​if​ ​(sum​ ​>​ ​10​ ​&&​ ​x​ ​==​ ​0){
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​i​ ​=​ ​1;
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​x​ ​=​ ​sum;
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​sum​ ​=​ ​0;
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​}
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​}
​ ​​ ​​ ​​ ​​ ​​ ​​ ​​ ​return((int)sum);
​ ​​ ​​ ​​ ​}
}

它告诉您它期望找到一个采用 int 参数的方法,但您已声明您的方法采用 long。虽然您可以将 int 传递给期望 long 的方法,但方法 signature 不同,因此未找到预期的签名。

public​ ​static​ ​int​ ​answer(long​ ​x)

应该是

public​ ​static​ ​int​ ​answer(int​ ​x)

编辑:根据评论中的讨论,这看起来像是测试用例中的错误,因为问题明确指出 long 并且答案预先填充了 long 参数。

public static method answer with parameters (int) not found in com.google.challenges.Answer

尝试使用int作为方法参数。解决方案处理期望该方法需要一个 int 参数。

正确方法头:

public​ ​static​ ​int​ ​answer(int​ ​x)

对于那些好奇的人,这是我使用的答案,它通过了所有测试用例。

package com.google.challenges; 

public class Answer {   
    public static int answer(int x) { 

        int placeholder = 0, sum = 0;

        for(int i = 1; x > 0 ; i++){
            placeholder = x % (int)(Math.pow(10,i));
            x -= placeholder;
            sum += placeholder / (int)(Math.pow(10, i - 1));
            if (sum > 10 && x == 0){
                i = 0;
                x = sum;
                sum = 0;
                continue;
            }
            if (sum < 10 && x == 0){
            break;
            }
        }
    return((int)sum);
    }
}