Skip to content

Commit

Permalink
[Math] fix solutions for Palindrome Number, Single Number II, and Sum…
Browse files Browse the repository at this point in the history
… Two Integers
  • Loading branch information
Yi Gu committed Aug 4, 2016
1 parent 40c8cdf commit 7c8d550
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 45 deletions.
25 changes: 16 additions & 9 deletions Math/PalindromeNumber.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,30 @@
*
* Time Complexity: O(1), Space Complexity: O(1)
*/
class Solution {

class PalindromeNumber {
func isPalindrome(x: Int) -> Bool {
if x < 0 {
guard x >= 0 else {
return false
}

var chars: [Character] = [Character](String(x).characters)
var b = 0
var e = chars.count - 1
var x = x
var div = 1

while b < e {
if chars[b] != chars[e] {
while (x / div >= 10) {
div = div * 10
}

while (x > 0) {
var left = x / div
var right = x % 10

if (left != right) {
return false
}

b += 1
e -= 1
x = (x % div) / 10
div = div / 100
}

return true
Expand Down
3 changes: 2 additions & 1 deletion Math/SingleNumberII.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@
*
*/

class Solution {
class SingleNumberII {
func singleNumber(nums: [Int]) -> Int {
var ans = 0
var sum = 0

for i in 0 ..< 64 {
sum = 0
let tmp = (1 << i)
Expand Down
36 changes: 1 addition & 35 deletions Math/SumTwoIntegers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,38 +16,4 @@ class SumTwoIntegers {
}
return a
}
}


/**
* Question Link: https://leetcode.com/problems/sum-of-two-integers/
* Primary idea: using ^ instead of +.
* 00 + 00 <-> ret
* 01 + 01 <-> ret ^ 10
* 01 + 00 <-> if ret & 01 != 0
* ret ^ 11
* else
* ret ^ 01
*
* Time Complexity: O(1), Space Complexity: O(1)
*/

class Solution {
func getSum(a: Int, _ b: Int) -> Int {
var ret = 0;
for i in 0 ..< 64 {
let tmp = 1 << i
if a & tmp == 0 && b & tmp == 0 {
continue
} else if a & tmp != 0 && b & tmp != 0 {
ret = ret ^ (tmp << 1)
} else {
if ret & tmp != 0 {
ret ^= (tmp << 1)
}
ret ^= tmp
}
}
return ret
}
}
}

0 comments on commit 7c8d550

Please sign in to comment.