【问题标题】:Remove leading digit from integer从整数中删除前导数字
【发布时间】:2017-09-22 07:27:03
【问题描述】:

我有一个整数值,例如-12345678,我想删除 前导数字,因此结果为-2345678

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

有什么简单的方法可以实现吗?

【问题讨论】:

  • 创建一个循环,将数字从右到左保存在另一个变量中,执行%10/10,不要保存最后一个。不知道有没有更好的办法
  • 12345678 中减去10000000 将得到2345678。你可以这样做,但你的字符串解决方案可能更好。

标签: swift integer


【解决方案1】:

一个可能的解决方案,使用简单的整数运算:

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 是给定数字的前导数字 而e10 的对应幂,例如对于n = 432,我们将 获取m = 4e = 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】:

    类似这样的:

    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
    

    【讨论】:

    • 或:if text.hasPrefix("-")... – 次要的 nitpick:零将被转换为空字符串。
    • @MartinR,我已经更新了这个例子。使用hasPrefix 更清洁。我也更新了处理0。感谢您的反馈。
    【解决方案3】:

    类似

    let intValue = 12345678
    let value = intValue % Int(NSDecimalNumber(decimal: pow(10, intValue.description.characters.count - 1)))
    //value = 2345678
    

    【讨论】:

      【解决方案4】:
      let n = -123456
      let m = n % Int(pow(10, floor(log10(Double(abs(n))))))
      

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

      【讨论】:

      • n = 0n = Int.min 导致崩溃(可能相关也可能不相关)
      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2013-03-31
      • 2014-06-25
      相关资源
      最近更新 更多