首页 > 解决方案 > 如何从十进制数的二进制表示中计算所有有效数字?像 1011 到 1110 这也是一个有效的数字

问题描述

例子是

美国广播公司

1 2 3

369 428 797

我们可以考虑二进制的 A=01 和 B=10。然后,有两种可能的方法:交换 A 的两位和 B 的两位(二进制表示为 As=10,Bs=01,十进制表示为 2 和 1)或不改组任何位。

数字 2 以相同的方式完成,但不知道该怎么做......在 C++ 代码中是否有任何我遗漏的基本想法

我可以使用代码找到字符串的所有组合来解决这个问题......但这将花费太多时间,因为 10^9 时间限制是 1s

此代码显示字符串的所有组合

#include <stdio.h>
#include <string.h>

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}

/* Function to print permutations of string
 This function takes three parameters:
 1. String
 2. Starting index of the string
 3. Ending index of the string. */
void permute(char *a, int l, int r)
{
  int i;
  if (l == r)
    printf("%s\n", a);
  else
  {
    for (i = l; i <= r; i++)
    {
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i)); //backtrack
    }
  }
}

/* Driver program to test above functions */
int main()
{
  char str[] = "10000000000111111110101010101010101";
  int n = strlen(str);
  permute(str, 0, n-1);
  return 0;
}

标签: c++theory

解决方案


推荐阅读