注册 登录
编程论坛 C++教室

算法做回文数

lucashl 发布于 2022-01-16 18:59, 1698 次点击
写一个程序,给定一个n(2<n<=10或n=16)进制数m。求最少几步可以得到回文数。如果在30步以内(包含30步)不可能得到回文数,则输出“Impossible"。
#include<iostream>
#include<cstring>
using namespace std;
int n,a[100],b[100],step=0,i;
void in(int a[])
{
  string s;
  cin>>n>>s;
  memset(a,0,sizeof(a));
  a[0]=s.length();
  for(int i=1;i<=a[0];i++)
    a[i]=s[i-1];
  for(int i=1;i<=a[0];i++)
    cout<<"s:"<<s[i]<<" ";
  cout<<endl;
}
bool check(int a[])
{
  for(i=1;i<=a[0];i++)
    if(a[i]!=a[a[0]-i+1])return false;
  return true;
}
void jia(int a[])
{
  int i,k;
  for(i=1;i<=a[0];i++) b[i]=a[a[0]-i+1];
  for(i=1;i<=a[0];i++) a[i]+=b[i];
  for(i=1;i<=a[0];i++)
  {
    a[i+1]+=a[i]/n;
    a[i]%=n;
  }
  for(int i=1;i<=a[0];i++) cout<<a[i];
  cout<<endl;
  if(a[a[0]+1]>0) a[0]++;
}
int main()
{
  in(a);
  if(check(a))
  {
      cout<<0<<endl;
      system("pause");
      return 0;
  }
  while(step<=30)
  {
      step++;
      jia(a);
      if(check(a))
      {
        cout<<step<<endl;
        system("pause");
        return 0;
    }
  }
  cout<<"Impossible"<<endl;
  system("pause");
  return 0;
}
请问这个程序哪里不对。
3 回复
#2
rjsp2022-01-16 20:31
你这个题目,只有神仙能看懂。
#3
diycai2022-01-18 14:26
描述确实看不懂,只能瞎改代码了
程序代码:
#include<iostream>
#include<cstring>
using namespace std;
int n,a[100]={0},b[100]={0},step=0,i;
void in(int a[])
{
  char s[100];
  int i;
  cin>>n>>s;
  memset(a,0,sizeof(a));
  a[0]=strlen(s);
  for(i=1;i<=a[0];i++)
  {
    if (s[i-1] & 0x40)
    {
        s[i-1] &= ~0x20;
        s[i-1] -= 7;
    }
    a[i]=s[i-1]-'0';
  }
  for(i=1;i<=a[0];i++)
      printf("%c", "0123456789ABCDEF"[a[i]]);
  cout<<endl;
}
bool check(int a[])
{
  for(i=1;i<=a[0];i++)
    if(a[i]!=a[a[0]-i+1])return false;
  return true;
}
void jia(int a[])
{
  int i,k;
  for(i=1;i<=a[0];i++) b[i]=a[a[0]-i+1];
  for(i=1;i<=a[0];i++) a[i]+=b[i];
  for(i=1;i<=a[0];i++)
  {
    a[i+1]+=a[i]/n;
    a[i]%=n;
  }
  if(a[a[0]+1]>0) a[0]++;
  for(i=1;i<=a[0];i++) printf("%c", "0123456789ABCDEF"[a[i]]);
  cout<<endl;
  
}
int main()
{
  in(a);
  if(check(a))
  {
      cout<<0<<endl;
      system("pause");
      return 0;
  }
  while(step<=30)
  {
      step++;
      jia(a);
      if(check(a))
      {
        cout<<step<<endl;
        system("pause");
        return 0;
    }
  }
  cout<<"Impossible"<<endl;
  system("pause");
  return 0;
}


[此贴子已经被作者于2022-1-18 14:41编辑过]

#4
lucashl2022-01-19 22:34
回复 3楼 diycai
谢谢,你的程序是对的。不过我不理解 printf("%c", "0123456789ABCDEF"[a[i]]);这句是干什么用的?
1