Created
April 30, 2013 02:13
-
-
Save sooop/5486227 to your computer and use it in GitHub Desktop.
Project Euler : Objc - 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
NSString *addString(NSString *a, NSString *b) | |
{ | |
NSString *result; | |
@autoreleasepool{ | |
NSMutableString *sumString = [NSMutableString string]; | |
NSUInteger l1, l2; | |
l1 = [a length] > [b length] ? [a length] : [b length]; | |
NSUInteger i,x,y,s,temp=0; | |
for(i=0;i<l1;i++) { | |
x = i >= [a length] ? 0 : [[a substringWithRange:NSMakeRange([a length] - i -1, 1)] intValue]; | |
y = i >= [b length] ? 0 : [[b substringWithRange:NSMakeRange([b length] - i -1, 1)] intValue]; | |
s = x + y + temp; | |
if(s>9) { | |
temp = s / 10; | |
s = s % 10; | |
} else { | |
temp = 0; | |
} | |
[sumString insertString:[@(s) stringValue] atIndex:0]; | |
} | |
if(temp) { | |
[sumString insertString:[@(temp) stringValue] atIndex:0]; | |
} | |
result = [sumString copy]; | |
} | |
return [result autorelease]; | |
} | |
NSString *reversedString(NSString *str) | |
{ | |
NSString *result; | |
@autoreleasepool{ | |
NSMutableString *temp = [NSMutableString string]; | |
NSUInteger l = [str length], i; | |
for(i=0;i<l;i++) { | |
[temp appendString:[str substringWithRange:NSMakeRange(l-i-1, 1)]]; | |
} | |
result = [temp copy]; | |
} | |
return [result autorelease]; | |
} | |
BOOL testNumber(int num) | |
{ | |
BOOL result = YES; | |
@autoreleasepool{ | |
int count = 0; | |
NSString *numString = (NSString*)[@(num) stringValue]; | |
while(count < 49) { | |
numString = addString(numString, reversedString(numString)); | |
if([numString isEqualToString:reversedString(numString)]) { | |
result = NO; | |
break; | |
} | |
count ++; | |
} | |
} | |
return result; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
@autoreleasepool{ | |
int count = 0; | |
int i=1; | |
while(i<10001) { | |
if(testNumber(i)) count++; | |
i++; | |
} | |
NSLog(@"%d", count); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment