代码之家  ›  专栏  ›  技术社区  ›  Evgeniy Kleban

从整数中删除前导数字

  •  1
  • Evgeniy Kleban  · 技术社区  · 8 年前

    -12345678 前导数字,因此结果为 -2345678 .

    可以将其转换为字符串并删除1个字符,然后删除1个符号。

    4 回复  |  直到 8 年前
        1
  •  4
  •   Martin R    8 年前

    使用简单整数算法的可能解决方案:

    func removeLeadingDigit(_ n: Int) -> Int {
        var m = n.magnitude
        var e = 1
        while m >= 10 {
            m /= 10
            e *= 10
        }
        return n - n.signum() * Int(m) * e
    }
    

    在循环结束时, m e 是的相应幂 10 ,例如 n = 432 收到 m = 4 e = 100

    print(removeLeadingDigit(0))    // 0
    print(removeLeadingDigit(1))    // 0
    print(removeLeadingDigit(9))    // 0
    print(removeLeadingDigit(10))   // 0
    print(removeLeadingDigit(18))   // 8
    print(removeLeadingDigit(12345))    // 2345
    
    print(removeLeadingDigit(-12345))   // -2345
    print(removeLeadingDigit(-1))       // 0
    print(removeLeadingDigit(-12))      // -2
    
    print(Int.max, removeLeadingDigit(Int.max)) // 9223372036854775807 223372036854775807
    print(Int.min, removeLeadingDigit(Int.min)) // -9223372036854775808 -223372036854775808
    
        2
  •  1
  •   Rashwan L    8 年前

    let value = -12345678
    var text = "\(value)"
    
    if text.hasPrefix("-") {
        let index = text.index(text.startIndex, offsetBy: 1)
        text.remove(at: index)
    } else if text.characters.count > 1 {
        let index = text.index(text.startIndex, offsetBy: 0)
        text.remove(at: index)
    }
    

    输出:

    value = -12345678 will print out -2345678
    value = 12345678 will print out 2345678
    value = 0 will print out 0
    
        3
  •  1
  •   hbk    8 年前

    let intValue = 12345678
    let value = intValue % Int(NSDecimalNumber(decimal: pow(10, intValue.description.characters.count - 1)))
    //value = 2345678
    
        4
  •  1
  •   nyg    8 年前
    let n = -123456
    let m = n % Int(pow(10, floor(log10(Double(abs(n))))))
    

    资料来源: https://stackoverflow.com/a/4319868/5536516