Skip to content

Instantly share code, notes, and snippets.

@atierian
Last active June 19, 2021 19:02
Show Gist options
  • Select an option

  • Save atierian/a5a0eb06eb62cab614d5dcb151ae178b to your computer and use it in GitHub Desktop.

Select an option

Save atierian/a5a0eb06eb62cab614d5dcb151ae178b to your computer and use it in GitHub Desktop.
import Foundation
import XCTest
infix operator ^^ : AdditionPrecedence
extension Int {
/// Add `n` to each digit, exclude carry. e.g.
/// ~~~
/// let shifted = 1945.shiftedUp(by: 2) // 3167
/// ~~~
/// - Parameter n: Shift each digit up by `n`
/// - Returns: Shifted `Int`
func shiftedUp(by n: Int) -> Int {
var workingCopy = self
var solution = 0
var digitFactor = 1
while workingCopy > 0 {
let (quotient, remainder) = workingCopy.quotientAndRemainder(dividingBy: 10)
workingCopy = quotient
solution += ((remainder + n) % 10) * digitFactor
digitFactor *= 10
}
return solution
}
/// Add `n` to each digit, exclude carry
/// ~~~
/// var number = 1945
/// number.shiftUp(by: 2) // 3167
/// ~~~
/// - Parameter n: Shift each digit up by `n`
mutating func shiftUp(by n: Int) {
self = shiftedUp(by: n)
}
/// `lhs` shifted each digit up by `rhs`, exclude carry. e.g.
/// - Parameters:
/// - lhs: `Integer` to shift
/// - rhs: Shift each digit up by `rhs`
/// - Returns: Shifted `Int`
static func ^^ (lhs: Self, rhs: Self) -> Self {
lhs.shiftedUp(by: rhs)
}
}
// MARK: Tests
class DigitShiftTests: XCTestCase {
let number = 19381723
func testShifted() {
let shiftedByTwo = number.shiftedUp(by: 2)
XCTAssertEqual(shiftedByTwo, 31503945)
let shiftedByFive = number ^^ 5
XCTAssertEqual(shiftedByFive, 64836278)
}
func testShift() {
var copy = number
copy.shiftUp(by: 2)
XCTAssertEqual(copy, 31503945)
}
}
DigitShiftTests.defaultTestSuite.run()
// MARK: Usage
1945.shiftedUp(by: 2) // 3167
1945 ^^ 2 // 3167
123456789123456789.shiftedUp(by: 3) // 456789012456789012
123456789123456789 ^^ 3 // 456789012456789012
var number = 1945
number.shiftUp(by: 2) // 3167
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment