在Swift中查找数字的数字总和

时间:2015-04-06 06:32:04

标签: swift

有谁知道如何获取Swift中数字中所有数字的总和?

例如,使用数字845会产生17

6 个答案:

答案 0 :(得分:11)

更新: Swift 4或更高版本

let string = "845"
let sum = string.compactMap{Int(String($0))}.reduce(0, +)
print(sum) // 17

let integer = 845
let sumInt = String(integer).compactMap{Int(String($0))}.reduce(0, +)
print(sumInt) // 17

答案 1 :(得分:8)

这是一个仅使用简单整数运算的解决方案:

func digitSum(var n : Int) -> Int {
    var sum = 0
    while n > 0 {
        sum += n % 10 // Add least significant digit ...
        n /= 10   // ... and remove it from the number. 
    }
    return sum
}

println(digitSum(845)) // 17

Swift 3/4的更新:

func digitSum(_ n : Int) -> Int {
    var n = n
    var sum = 0
    while n > 0 {
        sum += n % 10 // Add least significant digit ...
        n /= 10   // ... and remove it from the number.
    }
    return sum
}

print(digitSum(845)) // 17

另一个实现,只是为了好玩:

func digitSum(_ n : Int) -> Int {
    return sequence(state: n) { (n: inout Int) -> Int? in
            defer { n /= 10 }
            return n > 0 ? n % 10 : nil
        }.reduce(0, +)
}

答案 2 :(得分:2)

Swift 3中的递归解决方案!

func digitSum(of number: Int) -> Int
{
if(number < 10)
    {
    return number
    }
    else
        {
        return number % 10 + digitSum(of: (number/10))
        }
}

答案 3 :(得分:1)

为了完整起见,对于那些希望看到或理解基于数学的方法的人来说,这是一个基于实数的函数技术,移植到Swift。

这是计算Swift中整数数字的最有效方法。我不建议使用它。我个人会使用@LeoLDbus map / reduce回答这个问题,因为它非常酷,并且说明了一套功能强大的Swift功能但是还是@MartinR整数mod / divide的答案,因为它简单明了,整数运算的相对速度快

Cocoa和UIKit拥有必要的数学方法,因此您可能需要导入其中一个包。

func sumDigits(var i : Int) -> Int {
    var sum = 0
    var nDigits = floor(log10(Double(i))) + 1
    for var r = nDigits; r > 0; r-- {
        var p = pow(10, r - 1)
        var d = floor(Double(i) / p)
        sum += Int(d)
        i -= Int(d * p)
    }
    return sum
}

答案 4 :(得分:0)

对于swift4,请尝试以下功能:

func sumDigits(num: Int) -> Int {
    return String(num).compactMap { Int(String($0)) }.reduce(0, +)
}

答案 5 :(得分:0)

将其分为两部分:

  1. digits
public extension UnsignedInteger {
  /// The digits that make up this number.
  /// - Parameter radix: The base the result will use.
  func digits(radix: Self = 10) -> [Self] {
    sequence(state: self) { quotient in
      guard quotient > 0
      else { return nil }

      let division = quotient.quotientAndRemainder(dividingBy: radix)
      quotient = division.quotient
      return division.remainder
    }
    .reversed()
  }
}
XCTAssertEqual(
  (867_5309 as UInt).digits(),
  [8,6,7, 5,3,0,9]
)
XCTAssertEqual(
  (0x00_F0 as UInt).digits(radix: 0b10),
  [1,1,1,1, 0,0,0,0]
)
XCTAssertEqual(
  (0xA0_B1_C2_D3_E4_F5 as UInt).digits(radix: 0x10),
  [10,0, 11,1, 12,2, 13,3, 14,4, 15,5]
)
XCTAssertEqual(
  (0o00707 as UInt).digits(radix: 0o10),
  [0b111, 0, 0b111]
)
  1. sum
public extension Sequence where Element: AdditiveArithmetic {
  var sum: Element? { reduce(+) }
}
public extension Sequence {
  /// The first element of the sequence.
  /// - Note: `nil` if the sequence is empty.
  var first: Element? {
    var iterator = makeIterator()
    return iterator.next()
  }

  /// - Returns: `nil` If the sequence has no elements, instead of an "initial result".
  func reduce(
    _ getNextPartialResult: (Element, Element) throws -> Element
  ) rethrows -> Element? {
    guard let first = first
    else { return nil }

    return try dropFirst().reduce(first, getNextPartialResult)
  }
}
XCTAssertEqual([1, 2, 3].sum, 6)
XCTAssertEqual([0.5, 1, 1.5].sum, 3)
XCTAssertNil([CGFloat]().sum)