[ create a new paste ] login | about

Link: http://codepad.org/QFVAJhvN    [ raw code | output | fork | 1 comment ]

mohit_at_codepad - C, pasted on Jun 15:
// Increment a very large unsigned number by one
#include <stdio.h>
#include <string.h>

void incrementUnsignedIntByOneAndPrint(const char *s) {
  // Sanity checks like s is not null etc
  int i;
  int len = strlen(s);
  char *inc = malloc(len + 2);
  inc[len] = inc[len+1] = '\0';
  for(i = 0; i <= len; ++i) {
    int d = i;
    // Sanity checks like s[i] is a digis (isnum from ctype)
    while(s[i] == '9') i++;
    if('\0' == s[i]) {
      int offset = 0;
      // increment last digit and add n9s zeros
      if(0 == d) inc[offset++] = '1';
      else ++inc[d-1];
      if(d < i) memset(inc+offset+d, '0', i-d);
    } else {
      // copy all numbers
      if(d < i) memset(inc+d, '9', i-d);
      inc[i] = s[i];
    }
  }
  printf("Input  = %s\n", s);
  printf("Output = %s\n", inc);
  printf("\n");
}

int main() {
  incrementUnsignedIntByOneAndPrint("0");
  incrementUnsignedIntByOneAndPrint("1");
  incrementUnsignedIntByOneAndPrint("9");
  incrementUnsignedIntByOneAndPrint("100");
  incrementUnsignedIntByOneAndPrint("101");
  incrementUnsignedIntByOneAndPrint("109");
  incrementUnsignedIntByOneAndPrint("199");
  incrementUnsignedIntByOneAndPrint("999");
  incrementUnsignedIntByOneAndPrint("9999999999999999999999999999");
  incrementUnsignedIntByOneAndPrint("9999999999999999997999999999");
  incrementUnsignedIntByOneAndPrint("9991999993999999999799999999");
  incrementUnsignedIntByOneAndPrint("1111111111111111111111111111");
  incrementUnsignedIntByOneAndPrint("0000000000000000000000000000");
  return 0;
}


Output:
Input  = 0
Output = 1

Input  = 1
Output = 2

Input  = 9
Output = 10

Input  = 100
Output = 101

Input  = 101
Output = 102

Input  = 109
Output = 110

Input  = 199
Output = 200

Input  = 999
Output = 1000

Input  = 9999999999999999999999999999
Output = 10000000000000000000000000000

Input  = 9999999999999999997999999999
Output = 9999999999999999998000000000

Input  = 9991999993999999999799999999
Output = 9991999993999999999800000000

Input  = 1111111111111111111111111111
Output = 1111111111111111111111111112

Input  = 0000000000000000000000000000
Output = 0000000000000000000000000001



Create a new paste based on this one


Comments:
posted by PhoeniX888 on Jul 19
void Add_val(char * name)
{
int l = strlen(name);
int x = 0;
char *res = new char[l];
strcpy(res,name);
res = res + l -1;
while(*res == '9')
{
*res = '0';
res--;
x++;
continue;
}
if(x == l)
{
char *sr = new char [l+1];
sr[0] = '1';
sr[1] = '\0';
printf("Input:: %s\n" ,name);
printf ("Output:: %s\n",strcat(sr,++res));
}
else
{
*res = *res + '1' - '0' ;
printf("Input:: %s\n" ,name);
printf ("Output:: %s\n",res = res - (l -x - 1));
}
}
reply