简体   繁体   English

在Swift中像String一样连接Int?

[英]Concatenate Int like String in Swift?

I need Something like 我需要类似的东西

var a = 1
var b = 2
var c = a + b should be 12 (Int) instead of 3.

var a = 12
var b = 34
var c = a + b should be 1234 (Int) instead of 46.

I am not figuring out how can we do this for any number? 我不知道我们怎么能为任何数字做这个?

One way is to convert two both Int to String, concatenate and covert it again that String to Int, but I don't think it's efficient. 一种方法是将两个Int转换为String,连接并再次将String转换为Int,但我不认为它是有效的。

Thank you in advance if you have a solution. 如果您有解决方案,请提前感谢您。

12+34 = 12*10^2 + 34 = 1200+34 = 1234 12 + 34 = 12 * 10 ^ 2 + 34 = 1200 + 34 = 1234

func logC(val: Double, forBase base: Double) -> Double {
    return log(val)/log(base)
}

var a = 10
var b = 0
let x = b == 10 ? 2 : b == 0 ? 1 : ceil(logC(val: Double(b), forBase: 10))
var c = Int(Double(a) * pow(10, x) + Double(b))
print(c)

You can write something like this: 你可以写这样的东西:

extension Int {
    func concatenateDecimalDigits(in other: Int) -> Int {
        let scale: Int
        switch other {
        case 0...9:
            scale = 10
        case 10...99:
            scale = 100
        case 100...999:
            scale = 1000
        case 1000...9999:
            scale = 10000
        case 10000...99999:
            scale = 100000
        case 100000...999999:
            scale = 1000000
        //You need to add more cases if you need...
        //...
            //...
        default:
            scale = 0   //ignore invalid values
        }
        return self * scale + other
    }
}
var a = 1
var b = 2
print( a.concatenateDecimalDigits(in: b) ) //->12
a = 12
b = 34
print( a.concatenateDecimalDigits(in: b) ) //->1234
a = 122344
b = 9022
print( a.concatenateDecimalDigits(in: b) ) //->1223449022

You can write some logic to calculate scale without switch , but that does not make much difference. 您可以编写一些逻辑来计算无需switch scale ,但这并没有太大的区别。

General solution for any two Int : 任何两个Int一般解决方案:

You will need to calculate number of digits for calculate multiplier as: 您需要计算计算乘数的位数,如下所示:

func numberOfDigits(_ num: Int) -> Int {
    var count = 0
    var number = num
    while number > 0 {
        number = number / 10
        count += 1
    }
    return count
}

Use it as: 用它作为:

    let a = 11
    let b = 24

    let noOfDigit = numberOfDigits(b)
    let multiplier = pow(Double(10), Double(noOfDigit))
    let c = a * Int(multiplier) + b
    print(c)

And, in one line as: 并且,在一行中:

    let c = a * Int(pow(Double(10), Double(numberOfDigits(b)))) + b

You can do it with simple conversion like below: 您可以通过以下简单转换来完成:

var a = 1
var b = 2
var c = Int("\(a)\(b)") // Result 12

var a1 = 12
var b1 = 34
var c1 = Int("\(a1)\(b1)")  // Result 1234


var a2 = 122344
var b2 = 9022
var c2 = Int("\(a2)\(b2)") // Result 1223449022

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

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