今天回答某位博主悬赏的题目, 我觉得我代码写的挺好的,很有价值, 脑力劳动嘛, 发个博客保存一下
收获
提示:递归还真不适应人脑,想半天
- 代码谁都能写出来,但是自己写的就感觉很有成就感
- 大概花了快一个小时了,保存一下
- 话说悬赏的问题, 解题的时候也没采纳任何答案, 那你悬赏给啥, 抠门
package com.ajieyao.modules;
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
Yang yang = new Yang(3,4,5);
yang.printTriangle();
System.out.println(yang.caculat());
yang.expandString();
int i = yang.expandCaculate();
System.out.println(i);
}
static class Yang{
private int a,b,n;
private int[][] arr;
public Yang() {
}
public Yang(int a, int b, int n) {
this.a = a;
this.b = b;
this.n = n;
this.arr = getTriangle(n);
}
private double caculat(){
return Math.pow(a+b, n);
}
private void printTriangle(){
for (int i = 0; i < this.arr.length; i++) {
System.out.println(Arrays.toString(this.arr[i]));
}
}
private int[][] getTriangle(int n) {
int[][] array = new int[n+1][];
for (int i = 0; i < array.length; i++) {
array[i] = getNextRow(i);
}
return array;
}
private int[] getNextRow(int n) {
if(n == 0){
int[] a = {1};
return a;
}
if(n == 1){
int[] a = {1,1};
return a;
}
if(n == 2){
int[] a = {1,2,1};
return a;
}
int[] row = getNextRow(n-1);
int[] ints = new int[row.length + 1];
//第一个数字不需要计算 就取1
ints[0] = 1;
//sum存储的是上一个数组的计算结果,从一个开始,每次计算当前元素与后一个元素的和
int[] sum = new int[row.length];
for (int i = 0; i < row.length; i++) {
int s = 1;
//最后一个数字不需要计算 就取本身
if(i == row.length-1){
s = row[i];
}else{
s = row[i]+row[i+1];
}
sum[i] = s;
}
for (int i = 0; i < sum.length; i++) {
ints[i+1] = sum[i];
}
return ints;
}
private String expandString(){
StringBuffer sb = new StringBuffer("");
int[] row = this.arr[this.arr.length-1];
int c = this.n;
for (int i = 0; i < row.length; i++) {
int n = row[i];
sb.append(n);
if(c != 0){
sb.append("*");
sb.append(a);
sb.append("^");
sb.append(c);
}
if(i != 0){
sb.append("*");
sb.append(b);
sb.append("^");
sb.append(i);
}
if(i != row.length - 1){
sb.append(" + ");
}
c--;
}
System.out.println(sb);
return sb.toString();
}
private int expandCaculate(){
int[] row = this.arr[this.arr.length-1];
int c = this.n;
int count = 0;
for (int i = 0; i < row.length; i++) {
int n = row[i];
count += n*Math.pow(a, c)*Math.pow(b, i);
c--;
}
return count;
}
}
}