0
\$\begingroup\$

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;
}
\$\endgroup\$
3
\$\begingroup\$

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.

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

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...

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.