-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
/// 66. Plus One | ||
/// Given a non-empty array of digits representing a non-negative integer, plus one to the integer. | ||
/// The digits are stored such that the most significant digit is at the head of the list, and each | ||
/// element in the array contain a single digit. | ||
/// You may assume the integer does not contain any leading zero, except the number 0 itself. | ||
|
||
import XCTest | ||
|
||
/// Approach: Math | ||
func plusOne(_ digits: [Int]) -> [Int] { | ||
var digits = digits | ||
var carry = 1 | ||
for i in stride(from: digits.count - 1, through: 0, by: -1) { | ||
digits[i] += carry | ||
if digits[i] > 9 { | ||
digits[i] = digits[i] % 10 | ||
carry = 1 | ||
} else { | ||
carry = 0 | ||
} | ||
} | ||
if carry == 1 { | ||
digits.insert(1, at: 0) | ||
} | ||
return digits | ||
} | ||
|
||
class Tests: XCTestCase { | ||
func testExample() { | ||
let digits = [1, 2, 3] | ||
XCTAssertEqual(plusOne(digits), [1, 2, 4]) | ||
} | ||
} | ||
|
||
Tests.defaultTestSuite.run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> | ||
<playground version='5.0' target-platform='macos' executeOnSourceChanges='false'> | ||
<timeline fileName='timeline.xctimeline'/> | ||
</playground> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters