简体   繁体   中英

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.

Thank you in advance if you have a solution.

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.

General solution for any two 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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