Use iterative method to get the maximum number of 1 to n bits

Source: Internet
Author: User

This is the Huang Teacher Sword Point of offer above the 12th question, this question first notice cannot use the integer int type as the operand, because N is large when obviously overflows. This big data is generally used as a string to represent.

The direct method is: 1. For the addition of strings, it involves cyclic carrying and jumping out of judgment.

2. Print out the string, note that printing 01 is legal, otherwise you need to add additional judgment.

Another idea is that the output of these numbers is actually an n-bit full array. Each bit of the number has 0~9, which is possible in 10, so that every time the n bit is set, the n+1 bit of the iteration is set.

voidPrintArray (Char*ptr,intlength) {    BOOLFlag =false;  for(size_t i=0; i<length; ++i) {if(Ptr[i]! ='0'||flag) {Flag=true; cout<<Ptr[i]; }} cout<<Endl;}voidExhaustiverecursive (Char*ptr,intLengthintN) {    if(n = = Length-1) {PrintArray (ptr, length); return ; }     for(size_t i=0; i<Ten; ++i) {ptr[n+1] = i+'0'; Exhaustiverecursive (ptr, length, n+1); }}voidPrintnmaxrecursive (intN) {    if(n = =0)    {        return; }    Char*number_array =New Char[n+1];  for(size_t i =0; i<Ten; i++) {number_array[0] = i+'0'; Exhaustiverecursive (Number_array, N,0); }    Delete[] number_array;}
View Code

The above is the iterative method of their own attempt, not through a lot of use case testing, for reference only.

Use iterative method to get the maximum number of 1 to n bits

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.