【问题标题】:Problem using shifting bit (check if a binary number is palindrome)使用移位问题(检查二进制数是否为回文)
【发布时间】:2019-07-20 09:06:24
【问题描述】:

我需要有关检查二进制数是否为回文的代码的帮助。假设输入是 21 (10101)。在函数中我这样做:

-将num1的值复制到num2

-现在 num1 是 00010101 而 num2 是 00010101

-shift(right) num1 的位,而 num1>0

-现在 num1 是:00000000|10101000 而 num2 是 00010101|00000000

-将num1的位(左)移一位

-现在 num1 是:00000001|01010000 而 num2 是 00010101|00000000

-现在 while num1 != num2 我比较位并将 num1 左移和 num2 右移,每个循环。

-比较示例:

00000001|01010000

00010101|00000000
       |
       V
       1==1

下一个循环比较是 0==0

所以我的代码如下。我有一个问题,因为我不知道如何停止最后一段时间(while 条件:num1!= num2 && flag==true)。显然我写的条件不是正确的方法。但我不知道该怎么做。在这种特定情况下,如果它检查 5 位数,我想停止它。然后我想问一下我做的解决方案是否太难,以及是否有其他方法可以解决问题(ps:我觉得很难是正常的?因为我想解决它手动将十进制数转换为二进制使用 while (n>0) -> n%2,而不是记住数组中的位,并在数组上执行一个简单的算法来检查反向;但现在我想使用 > 运算符重做问题)。谢谢大家。

#include <iostream>

using namespace std;

int palindrome(unsigned short);

int main()
{
unsigned short num;

cout << "Inserisci un numero:\t";
cin >> num;

if (palindrome(num) == 1)
    cout << "Palindrome" << endl;
else
    cout << "Not palindrome" << endl;

cout << "\a";
return 0;
}

int palindrome(unsigned short num1)
{
unsigned short num2 = num1;
bool flag = true;

while (num1>0)
{
    num1 >>= 1;
}

num1 <<= 1;

while ((num1 != num2) && (flag == true))
{
    if ((num1 & 1) != (num2 & 1))
    {
        flag = false;
        break;
    }

    num1 <<= 1;
    num2 >>= 1;
}

return flag;
}

【问题讨论】:

    标签: c++ palindrome shift


    【解决方案1】:

    您提供的解决方案似乎很复杂。
    我会建议一种 naive 方法,您只需从整数的两端开始逐位迭代。
    只要这些位状态存在差异,您就可以断定它不是回文。
    如果达到整数的中间,那么我们可以断定它是一个回文。

    #include <stdio.h>
    #include <stdbool.h>
    
    bool
    palindrome(unsigned short num)
    {
      int bit_count=8*(int)sizeof(num);
      int half_bit_count=bit_count/2;
      for(int i=0; i<half_bit_count; ++i)
      {
        bool low=(num&(1u<<i))!=0;
        bool high=(num&(1u<<(bit_count-1-i)))!=0;
        if(low!=high)
        {
          return false;
        }
      }
      return true;
    }
    
    int
    main(void)
    {
      unsigned short i1=0x00A0;
      unsigned short i2=0x05A0;
      unsigned short i3=0xA005;
      unsigned short i4=0x005A;
      printf("%hx --> %d\n", i1, palindrome(i1));
      printf("%hx --> %d\n", i2, palindrome(i2));
      printf("%hx --> %d\n", i3, palindrome(i3));
      printf("%hx --> %d\n", i4, palindrome(i4));
      return 0;
    }
    

    【讨论】:

    • 好的。我会尝试。 (问题:你是怎么做到这么快的?我会认为我很愚蠢:0)
    • 我是 C++ 自学成才,我正在完成我的图书指南。我知道输入输出之类的概念,如果其他切换数组向量列表 OOP 类枚举命名空间指针 poliphormism 继承和算法,如选择排序、快速排序、搜索、二进制搜索递归 ecc。而且我确实按照我的书推荐的方式进行操作,但我经常很慢,而且我的思绪停止了。通常我不太清楚如何开始一个更困难的项目。正常吗?
    • 我已经编程多年了。正常的
    • @Riccardo 当你编程多年时,你会遇到很多情况。然后,每当一个问题与您已经完成的事情相似时,它就会响起警钟,您很快就会从您已经知道的知识中找到一个还不错的解决方案。但这并不特定于编程,只是时间问题,无论领域是什么。
    猜你喜欢
    • 2011-02-11
    • 2010-10-25
    • 1970-01-01
    • 2022-01-13
    • 2011-03-06
    • 2021-04-05
    • 2014-02-10
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多