fork(1) download
  1. #include <stdio.h>
  2. #include <string.h>
  3. /*
  4.  My algorithm read digits into char array
  5.  keep as chars
  6.  add 1 to far right digit and carry left as needed
  7.  for each pair of digit starting at outside pair and working toward
  8.  most inside pair or one,
  9.   if right pair digit is equal to left digit, bo to next inner pair
  10.   if left pair digit is larger than right, then replace right pair digit with left
  11.   if left pair digit is smaller than right, then cary one to digit just to left of right digit and then
  12.   copy left digit to right digit
  13.  
  14.  */
  15. #define BSIZE 1000001
  16.  
  17. char add_1(char c) {
  18. c++;
  19. if(c > '9') return '0';
  20. return c;
  21. }
  22.  
  23. void carry(char a[], int i) { // carry into a[i]
  24. while((a[i--] = add_1(a[i])) == '0');
  25. }
  26.  
  27. void do_case(char a[], int n) {
  28. int c9s = 0;
  29. for(int i = 0; i < n; i++) {
  30. if(a[i] != '9') break;
  31. c9s++;;
  32. }
  33. if(c9s == n) { // special case of all 9's
  34. printf("1");
  35. for(int i = 0; i < n-1; i++) {
  36. printf("0");
  37. }
  38. printf("1\n");
  39. return;
  40. }
  41. int left = 0;
  42. int right = n-1;
  43. carry(a, right); // add one to right side
  44.  
  45. while(right-left > 0) {
  46. if(a[right] > a[left]) {
  47. carry(a, right - 1);
  48. }
  49. a[right] = a[left];
  50. right--;
  51. left++;
  52. }
  53. char *p = a;
  54. while(*p == '0') p++; // removes leading zeros
  55. printf("%s\n", p);
  56. }
  57.  
  58. int main() {
  59. int cases;
  60. char a[BSIZE];
  61.  
  62. scanf("%d", &cases);
  63. for(int c = 1; c <= cases; c++) {
  64. scanf("%s", a);
  65. int n = (int)strlen(a);
  66. do_case(a, n);
  67. }
  68. }
  69.  
  70.  
Success #stdin #stdout 0s 10280KB
stdin
1
123

stdout
121