2017-09-22 14 views
1

整数値、たとえば-12345678を持っています。結果は-2345678になるように先頭の数字の を削除します。整数から先頭の桁を削除します

文字列に変換して1文字を削除した後、1記号を削除できます。

これを達成する簡単な方法はありますか?

+1

ループは '%10 'と'/10'をやって、右から左に別の変数に数値を保存し、保存しない作ります最後の一つ。 –

+1

'12345678'から' 10000000'を引いた結果、 '2345678'になります。あなたはそのように行くことができますが、あなたの文字列のソリューションはおそらく良いです。 – LuudJacobs

答えて

1

このような何か:

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 
+0

Or: 'if text.hasPrefix(" - ")' ... - マイナーニックピック:ゼロは空文字列に変換されます。 –

+0

@MartinR、私は例を更新しました。 'hasPrefix'を使用する方がずっときれいです。私は '0'を扱うように更新しました。フィードバックをお寄せいただきありがとうございます。 –

1

単純な整数演算を使用して

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

ような何かの可能な解決策:

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 = 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 
1
let n = -123456 
let m = n % Int(pow(10, floor(log10(Double(abs(n)))))) 

出典:https://stackoverflow.com/a/4319868/5536516

+2

'n = 0'と' n = Int.min'がクラッシュする(これは関連する場合もあります) –

関連する問題