Test: Interswap digits between two numbers

Question

Parameter 1 and 2 need to add in interchangeable between each other and both parameters are non-negative numbers. If the result > 100,000,000 return -1.

Example 1:

Parameter 1: 123456

Parameter 2: 879

Result: 182739456

Example 2:

Parameter 1: 12

Parameter 2: 56

Result: 1526

Solution

#pragma - mark 1. Interswap digit

-(int)interchangeNums:(int)num1 andNum2:(int)num2{

    NSMutableArray *arr1 = [self intToArray:num1];

    NSMutableArray *arr2 = [self intToArray:num2];

    NSMutableArray *totalarr = [NSMutableArray new];

    for(int i = 0,  j = 0 ; (i + j) <= (arr1.count + arr2.count)+ 1; i++, j++){

         if(i < arr1.count){

                [totalarr addObject:arr1[i]];

            }

        if(j < arr2.count){             
                [totalarr addObject:arr2[j]];        
         }  
   
} 
      int totalInt = [self arrayToInt:totalarr];    
      NSLog(@"num1 : %d", num1);     
      NSLog(@"num2 : %d", num2);     
      NSLog(@"totalInt : %d", totalInt);     
      
      if(totalInt > 100000000) 
          return -1; 
      else
          return totalInt;
} 

-(NSMutableArray *)intToArray:(int)num{     
      NSMutableArray *arr1 = [[NSMutableArray alloc] init];     
      for(int i = 0; num > 0; i++){
        int remainder = num % 10;
        [arr1 insertObject:[NSNumber numberWithInt: remainder] atIndex:0];
        num = num / 10;

    }

    

    return arr1;

}

-(int)arrayToInt:(NSMutableArray*)arr{
    int m=1;
    int restotal = 0;
    for(; arr.count > 0;){
        restotal = restotal + [[arr lastObject]integerValue] * m;
        [arr removeLastObject];
        m = m * 10;
    }
    return restotal;
}



Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s