給定任意一個正整數,求比這個數大且最小的“不重復數”,“不重復數”的含義是相鄰兩位不相同,例如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; }
總結:
思路