Sum of odd numbers
Given the triangle of consecutive odd numbers:
给定连续奇数的三角形:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
Calculate the sum of the numbers in the nth row of this triangle (starting at index 1) e.g.: (Input --> Output)
计算此三角形第n行中的数字之和(从索引1开始),例如:(输入–>输出)
1 --> 1
2 --> 3 + 5 = 8
solution:
class RowSumOddNumbers {
public static int rowSumOddNumbers(int n) {
return 0;
}
}
Sample Tests:
import static org.junit.Assert.*;
import org.junit.Test;
public class RowSumOddNumbersTest {
@Test
public void test1() {
assertEquals(1, RowSumOddNumbers.rowSumOddNumbers(1));
assertEquals(74088, RowSumOddNumbers.rowSumOddNumbers(42));
}
}
解决方法:
class RowSumOddNumbers {
public static int rowSumOddNumbers(int n) {
int sum=0;
for(int i=1;i<=n;i++){
sum=i*(int)(Math.pow(i, 2));
}
return sum;
}
}