make purely pure functions

This commit is contained in:
cediackermann 2026-06-08 10:39:44 +02:00
parent d7d9603bbc
commit 019f20a2c7
2 changed files with 31 additions and 45 deletions

View file

@ -1,50 +1,38 @@
import Foundation
//
// LeetCode.swift
// m323
//
// Created by cediackermann on 18.05.2026.
//
class LeetCode {
func hammingWeight(_ n: Int) -> Int {
return n == 0 ? 0 : (n & 1) + hammingWeight(n >> 1)
enum LeetCode {
static func hammingWeight(_ n: Int) -> Int {
n == 0 ? 0 : (n & 1) + hammingWeight(n >> 1)
}
func singleNumber(_ nums: [Int]) -> Int {
var result = 0
for num in nums {
result ^= num
}
return result
static func singleNumber(_ nums: [Int]) -> Int {
nums.reduce(0, ^)
}
func containsDuplicate(_ nums: [Int]) -> Bool {
return nums.count != Set(nums).count
static func containsDuplicate(_ nums: [Int]) -> Bool {
nums.count != Set(nums).count
}
func sortedSquares(_ nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted()
static func sortedSquares(_ nums: [Int]) -> [Int] {
nums.map { $0 * $0 }.sorted()
}
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int](repeating: 1, count: nums.count)
var prefix = [Int](repeating: 1, count: nums.count)
var suffix = [Int](repeating: 1, count: nums.count)
var runningProduct = 1
for i in 0..<nums.count {
prefix[i] = runningProduct
runningProduct *= nums[i]
static func productExceptSelf(_ nums: [Int]) -> [Int] {
let n = nums.count
var result = [Int](repeating: 1, count: n)
var prefix = 1
for i in 0..<n {
result[i] = prefix
prefix *= nums[i]
}
runningProduct = 1
for i in stride(from: nums.count - 1, through: 0, by: -1) {
suffix[i] = runningProduct
runningProduct *= nums[i]
result[i] = prefix[i] * suffix[i]
var suffix = 1
for i in stride(from: n - 1, through: 0, by: -1) {
result[i] *= suffix
suffix *= nums[i]
}
return result
}
}

View file

@ -5,9 +5,7 @@
// Created by cediackermann on 18.05.2026.
//
let code = LeetCode()
// print(code.hammingWeight(2_147_483_645))
// print(code.singleNumber([4, 1, 2, 1, 2]))
// print(code.containsDuplicate([1, 2, 3, 4]))
// print(code.productExceptSelf([-1, 1, 0, -3, 3]))
// print(LeetCode.hammingWeight(2_147_483_645))
// print(LeetCode.singleNumber([4, 1, 2, 1, 2]))
// print(LeetCode.containsDuplicate([1, 2, 3, 4]))
// print(LeetCode.productExceptSelf([-1, 1, 0, -3, 3]))