简体   繁体   English

将 NSInteger 连接到 NSInteger

[英]Concatenate a NSInteger to NSInteger

i'm making my own calculator and i came to the question.我正在制作我自己的计算器,我遇到了这个问题。
Sorry for newbie question , but I didn't find it.对不起,新手问题,但我没有找到。
How can i append a NSInteger to another NSInteger in Objective-C;如何在 Objective-C 中将 NSInteger 附加到另一个 NSInteger 中;
for example:例如:
5 + 5 = 55 5 + 5 = 55
6 + 4 + 3 = 643 6 + 4 + 3 = 643
etc.等等。

You have to convert them to strings.您必须将它们转换为字符串。 Here's one way:这是一种方法:

NSNumber *i1 = @6;
NSNumber *i2 = @4;
NSNumber *i3 = @3;

NSMutableString *str = [NSMutableString new];
[str appendString:[i1 stringValue]];
[str appendString:[i2 stringValue]];
[str appendString:[i3 stringValue]];

NSLog(@"result='%@", str);

However, having said all that, it's not clear to me why you are concatenating at all.然而,说了这么多,我不清楚你为什么要串联。

If they are a single digit (as in a calculator) you can simply do:如果它们是一位数(如在计算器中),您可以简单地执行以下操作:

NSInteger newNumber = (oldNumber * 10) + newDigit;

or in a method:或在一种方法中:

- (NSInteger)number:(NSInteger)currentNumber byAdding:(NSInteger)newDigit {
    //Assumes 0 <= newDigit <= 9
    return (currentNumber * 10) + newDigit;
}

If they have more than one digit you can make them into strings, concatenate them and convert back to integers or use simple arithmetic to find out the power of 10 you must multiply by.如果它们有多个数字,您可以将它们变成字符串,将它们连接起来并转换回整数或使用简单的算术来找出您必须乘以的 10 的幂。

EDIT: 6 + 4 + 3 Assuming a digit is provided at a time:编辑: 6 + 4 + 3 假设一次提供一个数字:

NSInteger result = [self number:[self number:6 byAdding:4] byAdding:3];

Purely arithmetic solution:纯算术解决方案:

- (NSInteger)powerOfTenForNumber:(NSInteger)number {
    NSInteger result = 1;
    while (number > 0) {
        result *= 10;
        number /= 10;
    }
    return result;
}


- (NSInteger)number:(NSInteger)currentNumber byAdding:(NSInteger) newNumber {
    return (currentNumber * [self powerOfTenForNumber:newNumber]) + newNumber;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM