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\$

2 Answers 2

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\$
1
  • \$\begingroup\$ What would your response be in an interview question, where I need to do it from scratch? \$\endgroup\$ Commented Jul 17, 2016 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\$
1
  • \$\begingroup\$ It creates a temp NSNumber object for conversion, not good for me. \$\endgroup\$ Commented Feb 25, 2017 at 15:11

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.