# Convert NSInteger into NSString

This is my sample code to convert a integer into string.

Is it very costly to do the multiple loops of [NSMutableString stringWithFormat:..]?

I.e should I just use appendString and get the NSString in reverse order and then do one for loop to reverse this "reverse string".

Is there any other faster/more elegant way?

NSString * intToString(NSInteger numberToConvert)
{
BOOL isNegative = (numberToConvert < 0);
if (isNegative)
{
numberToConvert = -1*numberToConvert;
}

NSMutableString *convertedString = [[NSMutableString alloc] init];

while(numberToConvert != 0)
{
convertedString = [NSMutableString stringWithFormat:@"%ld%@",numberToConvert%10,convertedString];
numberToConvert = numberToConvert/10;
}

if (isNegative)
{
convertedString = [NSMutableString stringWithFormat:@"-%@",convertedString];
}

return convertedString;
}


Umm… this is a complicated solution that makes no sense. Why not keep it simple?

NSString *intToString(NSInteger numberToConvert)
{
return [NSString stringWithFormat:@"%ld", numberToConvert];
}


If, on the other hand, the exercise is to implement your own solution from scratch, then I would consider it cheating to use NSMutableString stringWithFormat:. Either way, I would consider your solution to be a failed response in an interview situation.

• What would your response be in an interview question, where I need to do it from scratch? – Smart Home Jul 17 '16 at 17:30

I would go with

NSString *intToString(NSInteger numberToConvert) {

return [@(numberToConvert) stringValue];
}


Using NSNumber's stringValue method.

written without literals

return [[NSNumber numberWithInteger(numberToConvert)] stringValue];


Unless I'm misunderstanding the question. Which has been known to occur before...

• It creates a temp NSNumber object for conversion, not good for me. – Itachi Feb 25 '17 at 15:11