1

I have an integer value, for example -12345678, and I want to remove the leading digit, so that the result is -2345678.

One could convert it to string and remove 1 character, then remove 1 symbol.

Is there any simple way to achieve that?

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107
  • 1
    make a loop saving in another variable the numbers from right to left, doing `%10` and `/10`, and don't save the last one. Don't know if there's a better way – Shinra tensei Sep 22 '17 at 07:31
  • 1
    Subtracting `10000000` from `12345678` will result in `2345678`. You could go that way, but your string solution is probably better. – Luuuud Sep 22 '17 at 07:31

4 Answers4

4

A possible solution, using simple integer arithmetic:

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
}

At the end of the loop, m is the leading digit of the given number and e is the corresponding power of 10, e.g. for n = 432 we'll get m = 4 and e = 100. Some tests:

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
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

Something like this:

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)
}

Output:

value = -12345678 will print out -2345678
value = 12345678 will print out 2345678
value = 0 will print out 0
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • Or: `if text.hasPrefix("-")`... – Minor nitpick: Zero would be transformed to an empty string. – Martin R Sep 22 '17 at 09:56
  • @MartinR, I have updated the example. Much cleaner to use `hasPrefix`. I did also update to handle `0`. Thanks for the feedback. – Rashwan L Sep 22 '17 at 10:03
1

Something like

let intValue = 12345678
let value = intValue % Int(NSDecimalNumber(decimal: pow(10, intValue.description.characters.count - 1)))
//value = 2345678
hbk
  • 10,908
  • 11
  • 91
  • 124
1
let n = -123456
let m = n % Int(pow(10, floor(log10(Double(abs(n))))))

Source: https://stackoverflow.com/a/4319868/5536516

nyg
  • 2,380
  • 3
  • 25
  • 40