1. 程式人生 > 其它 >Problem:迴文平方

Problem:迴文平方

技術標籤:演算法c++

題目描述

迴文數是指數字從前往後讀和從後往前讀都相同的數字。

例如數字 12321 就是典型的迴文數字。

現在給定你一個整數 B,請你判斷 1∼300 之間的所有整數中,有哪些整數的平方轉化為 B 進位制後,其 B 進製表示是迴文數字。

輸入格式

一個整數 B。

輸出格式

  1. 每行包含兩個在 B 進位制下表示的數字。
  2. 第一個表示滿足平方值轉化為 B 進位制後是迴文數字那個數,第二個數表示第一個數的平方。
  3. 所有滿足條件的數字按從小到大順序依次輸出。

資料範圍

2 ≤ B ≤ 20,
對於大於 9 的數字,用 A 表示 10,用 B 表示 11,以此類推。

輸入樣例

在這裡插入圖片描述

輸出樣例

在這裡插入圖片描述

思路

短除法

程式程式碼

  1. 經典寫法
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

char get(int x)
{
    if(x <= 9)
        return x + '0';
    return x - 10 + 'A';
}

string base(int n, int b)
{
    string num;
    while(n)
    {
        num += get(n % b);
        n /
= b; } reverse(num.begin(), num.end()); return num; } bool check(string num) { for(int i = 0, j = num.size() - 1; i < j; ++ i, -- j) if(num[i] != num[j]) return false; return true; } int main() { int b; cin >> b; for(int i = 1; i <= 300;
++ i) { auto num = base(i * i, b); if(check(num)) cout << base(i, b) << ' ' << num <<endl; } return 0; }
  1. 使用棧的特性
#include <iostream>
#include <stack>
#include <cstring>
#include <algorithm>

using namespace std;

stack<char> s;

char change(int x) //元素轉換
{
    if(x <= 9)
        return x + '0';
    else
        return x - 10 + 'A';
}

string convert(int x, int b) //進位制轉換函式
{
    string str;
    while(x)
    {
        s.push(change(x % b)); //將餘數轉換後壓入棧
        x /= b;
    }
    int t = s.size();
    while(t--)
    {
        str += s.top(); //獲取棧頂元素
        s.pop(); //彈出棧頂元素
    }
    return str; //返回結果
}

bool check(string s) //判斷函式
{
    for(int i = 0, j = s.size() - 1; i < j; ++ i, -- j)
        if(s[i] != s[j])
            return false; //若不滿足迴文規則,直接結束函式
    return true;
}

int main()
{
    int b;
    cin >> b;
    for(int i = 1; i <= 300; ++ i)
    {
        auto s = convert(i * i, b); //轉換
        if(check(s)) //判斷
            cout << convert(i, b) << ' ' << s << endl; //輸出結果
    }
    return 0;
}
  • 若有問題,歡迎交流