java 求s=a+aa+aaa+aaaa+aa...a的值
public class qiuhe {
/**
*
* 求s=a+aa+aaa+aaaa+aa...a的值,
* 其中a是一個數字。例如2+22+222+2222+22222(此時共有5個數相加),幾個數相加有鍵盤控制。*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long a;
int n;
Scanner scanner=new Scanner(System.in);
System.out.print("請輸入數字a的值:");
a=scanner.nextLong();
System.out.print("請輸入相加的項數:");
n=scanner.nextInt();
System.out.println("s=a+aa+aaa+aaaa+aa...a的和為"+Sum(a, n));
}
public static long Sum(long a,int n) {
long sum = 0,b=0;
int i=0;
while (i<n) {
b+=a;
sum+=b;
a*=10;
i++;
}
return sum;
}
}