java语言实现,使用while循环,求1+11+111+1111+11111+111111.

2024-12-17 17:24:46
推荐回答(5个)
回答1:

int cal(){
int i=1;
int sum = 0;
while(i<=6){
int subsum = 0;
int flag = 1;
for(int j=1;jflag *= 10;
subsum += flag;
}
if(subsum == 0)
subsum = 1;
sum += subsum;
i++;
}
return sum;
}
其实不用循环这个题是很简单的,应该自己总结规律得到一个公式,尽量减轻计算机的工作量。

回答2:

public static void main(String[] args) {
int a=0, b=0,c=0;
while(c<6) {
b=b * 10+1;
a=a+b;
c++;
}
System.out.println(a);
}

回答3:

没有循环要求?
while(true){return 1+11+111+1111+11111+111111;}
要灵活点的:
int i=1;
int sum=1;
while(i<=6){
sum+=(Math.pow(10,i));
i++;
}
return sum;

回答4:

public class Test {
public static void main(String[] args) { int loopNum = 1;
int sum = 0;
int i = 1;
while (loopNum <= 6) {
if (loopNum > 1) i = i * 10 + 1;
sum += i;
loopNum++;

}

System.out.println(sum);

}
}

回答5:

int i = 1;
int s= 0;
while(i < 7){
s = s*10 +1;
i++;
}
System.out.println(s);