Print Pattern
Description
Write a program that reads an interger n, and then displays 2^0, 2^1, … 2^i-1, … 2^0 for each line, where i = n…1. For example, if n=4, the pattern is as follow:
Input
An integer n (1<=n<=15).
Ouput
The Pattern of height n.
Solution:
按照每行元素个数递增的顺序用stack依次存储数字,然后设置输出格式(宽度&靠右)并依次输出栈顶元素。
#include <iostream>
#include <stack>
#include <cmath>
#include <iomanip>
using namespace std;
int main() {
int m, i = 0;
cin >> m;
stack<int> num;
while(i < m) {
int j = 0;
while(j<i+1) {
num.push(pow(2, j));
j++;
}
j--;
while(j) {
j--;
num.push(pow(2, j));
}
i++;
}
i = 0;
while(!num.empty()) {
int time = 2*m-1;
for (int k = 0; k < i; k++) {
cout<<setiosflags(ios::right)<<setw(8);
cout << " ";
}
while(time--) {
cout<<setiosflags(ios::right)<<setw(8);
cout << num.top();
num.pop();
}
cout << endl;
i++;
m--;
}
cout << endl;
return 0;
}