独特的数字在C ++ [英] Unique numbers in C++

查看:184
本文介绍了独特的数字在C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有效地列出1和100。不过,我必须用相同的数字摆脱数字之间的数字。
例: 根据这个规则12是相同的21 13 31 14 41 所以循环也不会去了相同的号码。
我想一些技巧,如获得从1到100的所有号码,然后删除当前数字的排列找到。 我之所以这么问,是因为在很大程度上限制像100000将失败。 又如: 1​​24等于142,241,214,412,421

I'm trying to efficiently list numbers between 1 and 100. However I have to get rid of numbers with same digits.
Example: 12 according to this rule is the same of 21 13 is 31 14 is 41 so the for loop it won't go over the same numbers.
I'm thinking a few tricks such as getting all the numbers from 1 to 100 and then deleting the found permutations of current number. The reason I'm asking this because in large limits like 100000 it will fail. Another example: 124 is equal to 142,241,214,412,421

推荐答案

您可以使用递归。这个函数的原型是那么这样的:

You can apply recursion. Prototype of this function is then like:

print_digits(int num_of_remaining_digits,int start_from_digit, int current_number);

编辑:完成我present这里我的解决方法(我认为这不是从本·沃伊特和升输出顺序

for completion I present here my solution (i think it has better readbility than from Ben Voigt and ascending output order

void print_digits(int num_of_remaining_digits,int start_from_digit, int current_number)
{
  if(num_of_remaining_digits == 0) 
  {
    std::cout << current_number << std::endl;
    return;
  }

  for(int i=start_from_digit;i<=9;i++)
  {
     print_digits(num_of_remaining_digits-1,i,10*current_number+i);
  }
}

这里是测试code

and here is testing code

http://ideone.com/Xm8Mv

如何工作的吗?

这是递归的经典之一。首先是停止条件。再有就是主循环。
主要的循环,从 start_from_digit 去,因为所有生成的数字将在非递减顺序。例如,如果 CURRENT_NUMBER 15 ,它会调用 print_digits 蒙山

It is one of classics in recursion. First there is stopping condition. And then there is main loop.
Main loop where goes from start_from_digit because all generated digits will be in non decreasing order. For instance if current_number is 15 it will call print_digits whith

print_digits(num_of_remaining_digits-1,5,155)
print_digits(num_of_remaining_digits-1,6,156)
print_digits(num_of_remaining_digits-1,7,157)
print_digits(num_of_remaining_digits-1,8,158)
print_digits(num_of_remaining_digits-1,9,159)

在每次调用它会检查,如果我们达成结束丝毫 num_of_remaining_digits ,如果不继续从被压的 start_from_digit (第2参数) CURRENT_NUMBER

In each call it will check if we reached end whit num_of_remaining_digits and if not will continue from digit that is pushed as start_from_digit (2nd param) using current_number

这篇关于独特的数字在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆