找到第42个数字,其数字之和为42

时间:2014-06-02 18:17:38

标签: objective-c

我有另一个有趣的编程/数学问题。 我想写一个应用程序,找到其数字之和为42的第42个数字,我需要找到其数字之和为42的数字并添加到新数组以打印新数组中的第42个数字,其中有大约50个数字它的数字之和为42.感谢您抽出宝贵时间提供帮助。

@implementation AppDelegate

static NSArray *newArray ;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{


    int numberWithSum42;
    for (int i=69999;i<80000;i++)
    {
        int x=[self findTotalNumber:i];

        if(x==12){
             numberWithSum42=i;
            newArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:numberWithSum42], nil];
        }
        NSLog(@"%@",newArray);
    }
    [self print42ndVariable];
}
-(void)print42ndVariable{
    int j;
    int count = (int)[newArray count];
    for (j = 0; j < count; j++){
        NSLog (@"42nd variable of array   = %@", [newArray objectAtIndex: 42]);
    }

}
-(int)findTotalNumber:(int) n{
    int s=0;
    while (n>0)
    {
        int k=n%10;
        s=s+k;
        n=n/10;
    }
    NSLog(@"%i",s);
    return n;
}

@end

2 个答案:

答案 0 :(得分:0)

因为你想要所有的数字+打印第42号。

 static NSMutableArray * numberArray ;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

numberArray = [NSMutableArray array];
int exitJ;
for (int i=69999;i<80000;i++)
{
    int x=[self findTotalNumber:i];

    if(x==42){//You want the sum to be 42 and not 12??

         exitJ++;
        [numberArray addObject:[NSNumber numberWithInt:i]];
    }
    if(exitJ>=42)break; //Exit after getting 42 numbers

  }
  NSLog(@"%@", numberArray);
  [self print42ndVariable];
}

numberArray应该有42个数字。

答案 1 :(得分:0)

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
int requiredNumber;
int currentIndex;
int sumOfDigits;

//Assuming the limits you wnat are 69000<=x<80000

for (int i=69999;i<80000;i++)
{
    sumOfDigits= [self sum:i];

    if(i==42){
         currentIndex++;
    }
    if (currentIndex == 42){
         NSLog(i); //The number!
    }
}

}
-(void)sum:(int)number{
int digit,sum=0, temp;
    temp = number;

    while(temp > 0) {
        digit = temp%10;
        sum += digit;
        temp = temp/10;
    }
    NSLog(@"Sum of digits of %i = %i",number,sum);
    return sum;
}