我试图解决一个算法问题,我是新手,我正在尝试大量练习编程问题。所以我想构造一个单位矩阵 n*n。我想出了一个愚蠢的解决方案,它适用于 4*4 矩阵,但不适用于 5*5。我知道它奇怪的解决方案,当我看到它时,问题的解决方案真的很容易。我需要知道我做错了什么以便我可以学习,我的解决方案真的很愚蠢,在解决这些问题之后我会变得更好吗?
#include <iostream>
#include <vector>
#include <sstream>
#include <iomanip> // for setw, setfill
using namespace std;
int binary(int number);
int main()
{
vector<vector<int> > matrix;
cout<<"Please enter the size of the identity matrix"<<endl;
int n;
cin>>n;
matrix.resize(n);
for (int i=0; i<n;i++)
{
matrix[i].resize(n);
}
int steps = 1<<n-1;
int bin = binary(steps);
ostringstream binString;
binString <<bin;
if(binString.str().size()<n)
{
std::string dest = binString.str();
int nPaddings = n-binString.str().size();
if (nPaddings==0) nPaddings=1;
dest = std::string( nPaddings, '0').append( binString.str());
binString.str("");
binString<<dest;
}
for (int col = 0; col<n; col++)
{
if(col>=1)
{
steps= (int)steps/2;
int bin = binary(steps);
binString.str("");
binString << bin;
if(binString.str().size()<n)
{
std::string dest = binString.str();
int nPaddings = n-steps;
if (nPaddings==0) nPaddings=1;
dest = std::string( nPaddings, '0').append( binString.str());
binString.str("");
binString<<dest;
}
}
for (int row=0; row<n; row++)
{
matrix[col][row] =binString.str().at(row)-'0';
}
}
return 0;
}
int binary(int number) {
long rem,i=1,sum=0;
do
{
rem=number%2;
sum=sum + (i*rem);
number=number/2;
i=i*10;
}while(number>0);
return sum;
}