程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 求比指定數大且最小的“不重復數”問題

求比指定數大且最小的“不重復數”問題

編輯:關於C語言

給定任意一個正整數,求比這個數大且最小的“不重復數”,“不重復數”的含義是相鄰兩位不相同,例如1101是重復數,而1201是不重復數.

 

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#define NUMBER_STR_MAX_LENGTH (128)
unsigned find(unsigned);

int main(void)
{
    unsigned num = 0;

    printf("Please input Unsigned Number : ");
    if (scanf("%u", &num) != 1) {
        perror("input error!");
        return 1;
    }

    printf("%u\n", find(num));
    return 0;    
}

void str_reverse(unsigned char *str,unsigned length)
{
    unsigned char *prv = NULL;
    unsigned char *cur = NULL;
    unsigned char swap = '\0';

    for (prv = str, cur = str + (length-1)
            ; prv < cur; ++prv, --cur){
        swap = *prv;
        *prv = *cur;
        *cur = swap;
    }
}

unsigned find(unsigned number)
{
    unsigned char number_str[NUMBER_STR_MAX_LENGTH] = {'\0'};
    unsigned char *prv = NULL;
    unsigned char *cur = NULL;
    unsigned char *finded = NULL;
    unsigned int number_length = 0;
    unsigned int result = 0;  
    int carry = 0;

    ++number;
    number_length = sprintf(number_str, "%u", number);
    str_reverse(number_str, number_length);

    for (cur = number_str + (number_length-1), finded = number_str
            ; cur > finded - 1 ; --cur ){
    
        if (prv != NULL && *prv == *cur){
            finded = cur;
            carry = 1;
            do {
                *cur += carry;
                carry = (*cur - '0') / 10u;
                *cur = (*cur-'0') % 10u + '0';
                ++cur;
            } while (carry != 0 && cur < (number_str + number_length));
            if (carry > 0){
                *cur = '0' + carry ;
                ++number_length;
            }
        }
        prv = cur;
    }

    /* set reset as 010101 */
    for (carry = 0; cur > number_str - 1; --cur){
        *cur = carry + '0';
        carry ^= 1u;
    }
    str_reverse(number_str, number_length);
    sscanf(number_str,"%u",&result);
    return result;
}

 

總結:

思路

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved