java——数列求和

题目描述

求Sn=a+aa+aaa+…+aa…aaa(有n个a)之值,其中a是一个数字。 例如:2+22+222+2222+22222(n=5),n由键盘输入。

 令a=2,n=5求输出?

import java.util.*;
public class Main {
public static void main(String[] args)
{
	Scanner in = new Scanner(System.in);
	int n = in.nextInt();
	int  An = 0;
	int  Sn = 0;
	for(int i = 0;i < n; i++){
		An = An*10 + 2;
		Sn = Sn + An;
	}
	System.out.println(Sn);     
}
}
import java.util.*;
public class Main {
    public static void main(String[] args)
    {
    
	    Scanner in = new Scanner(System.in);

	    int n = in.nextInt();
	
	    int Sn = 0;    
                                         
	    StringBuffer sb = new StringBuffer();

	    for(int i = 1; i <= n; i++){
	        sb.append(2);
	        String b = new String(sb);
	        Sn = Sn + Integer.parseInt(b);
	        }

	    System.out.println(Sn);

    }
}

 

你可能感兴趣的:(java)