Recursive base converter

We solve the problem recursively, when we break it into smaller and smaller subproblems, until the solution becomes obvious.
There are three rules of recursion:

  1. Define a base case
  2. Change a state and move towards base case
  3. Call itself

Let’s see how they can be fulfilled using the base converter:

- (NSString *)recursiveBace: (NSInteger)number ToBase: (NSInteger)base
{
    NSArray *convert = @[@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"A", @"B", @"C", @"D", @"E", @"F"];
    NSMutableString *result = [[NSMutableString alloc]init];
    if (number < base) { //detect the base case
        [result appendString:convert[number]]; //then return a string from sequence
    } else {
        [result appendString:[self recursiveBace:number/base ToBase:base]]; //reduce problem size and change state
        [result appendString:convert[number%base]];
    }
    return result;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s