Java 如果编号为armstrong打印0,如果不是armstron打印1,则查找给定编号是否为armstrong编号
尝试以下代码,但不符合要求,如果阿姆斯特朗号码为0,如果不是阿姆斯特朗号码为1 建议实施该计划的纠正措施Java 如果编号为armstrong打印0,如果不是armstron打印1,则查找给定编号是否为armstrong编号,java,Java,尝试以下代码,但不符合要求,如果阿姆斯特朗号码为0,如果不是阿姆斯特朗号码为1 建议实施该计划的纠正措施 @Sanjyukta如果数字为armstrong,则您尚未分配isNumber=true,因此每次它都将返回false和0,并且不会更新i和isNumber的值。 下面的代码将更新isNumber和i值 if (temp == c) { isNumber = true; i = isNumber ? 0 : 1; }
@Sanjyukta如果数字为armstrong,则您尚未分配
isNumber=true
,因此每次它都将返回false
和0
,并且不会更新i
和isNumber
的值。
下面的代码将更新isNumber
和i
值
if (temp == c) {
isNumber = true;
i = isNumber ? 0 : 1;
}
System.out.println(isNumber + "\t" + i);
我问题的答案:使用三元运算符是可能的
public static void solution(int N)
{
int c=0,a,temp;
temp=N;
while(N>0)
{
a=N%10;
N=N/10;
c=c+(a*a*a);
}
if(temp == c)
{
boolean b = true;
c = (b) ? 1 : 0;
}
else
{
boolean b = false;
c = (b) ? 1 : 0;
}
System.out.println(c);
}
class Arm
{
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int N = s.nextInt();
@SuppressWarnings("unused")
Example ex= new Example();
ex.solution(N);
}
}
是时候启动调试器了。代码很难阅读的人:-)忍不住重写它(请参阅错误修复的现有答案)注意:您的算法只对3位数字有效。打印0如果是阿姆斯特朗数字,打印1如果不是阿姆斯特朗数字,我出错了?根据谨慎性,当它是阿姆斯特朗数时,不应该分配i=0?而不仅仅是
System.out.println((temp==c)?1:0)代码>(在while块之后)?例如,2
也是阿姆斯特朗号码(基于维基百科)的回答错误
public static void solution(int N)
{
int c=0,a,temp;
temp=N;
while(N>0)
{
a=N%10;
N=N/10;
c=c+(a*a*a);
}
if(temp == c)
{
boolean b = true;
c = (b) ? 1 : 0;
}
else
{
boolean b = false;
c = (b) ? 1 : 0;
}
System.out.println(c);
}
class Arm
{
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int N = s.nextInt();
@SuppressWarnings("unused")
Example ex= new Example();
ex.solution(N);
}
}