有2个算法题目,高手进来帮帮我
题目1 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。
题目2 :打印出如下图案(菱形)
*
***
******
********
******
***
*
------解决方案--------------------第1题:
public class Test1 {
public static void main(String[] args) {
int sum = 0;
int num;
int temp;
int a = 0;
String str = " ";
if (args != null && args.length > 0) {
num = Integer.parseInt(args[0]);
if (num > = 10) return;
sum = num;
while(num != 0) {
temp = num % 10;
str = " " + temp + str;
num --;
}
sum = Integer.parseInt(str) * sum;
}
System.out.println(sum);
}
}
------解决方案--------------------第1题:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print( "请输入需要几个数: ");
int k = sc.nextInt();
long sum = 0;
String s = "2 ";
StringBuffer sb = new StringBuffer();
for(int i = 0; i < k; i++){
sb.append(s);
sum += Long.parseLong(sb.toString());
}
System.out.println(sum);
}
******************
第2题:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print( "请输入需要几行(奇数): ");
int line = sc.nextInt();
line = (line & 1) == 0 ? line + 1 : line;
for(int i = 0 - line / 2; i <= line / 2; i++){
for(int j = 1; j <= line - 2 * Math.abs(i); j++){
System.out.print( "* ");
}
System.out.println();
}
}