Triangle number check
Description:
A triangle number is a number where n objects form an equilateral triangle (it's a bit hard to explain). For example, 6 is a triangle number because you can arrange 6 objects into an equilateral triangle:
1
2 3
4 5 6
8 is not a triangle number because 8 objects do not form an equilateral triangle:
1
2 3
4 5 6
7 8
In other words, the nth triangle number is equal to the sum of the n natural numbers from 1 to n.
Your task:
Check if a given input is a valid triangle number. Return true if it is, false if it is not (note that any non-integers, including non-number types, are not triangle numbers).
You are encouraged to develop an effective algorithm: test cases include really big numbers.
Assumptions:
You may assume that the given input, if it is a number, is always positive.
Notes:
0 and 1 are triangle numbers.
My Submit
func isTriangleNumber(_ number: Int) -> Bool {
if number < 0 {
return false
} else {
for i in 0...(number/2) {
if i + i * i == number * 2 {
return true
}
if i + i * i > number * 2 {
return false
}
}
}
return true
}
Best Practices
func isTriangleNumber(_ number: Int) -> Bool {
let val = 0.5 * sqrt(Double(8 * number + 1)) - 0.5
return rint(val) == val
}
Summary
poor math
Persistent Bugger.
Instructions
Write a function, persistence, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of times you must multiply the digits in num
until you reach a single digit.
For example:
persistence(for: 39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(for: 999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(for: 4) === 0 // because 4 is already a one-digit number
My Submit
func persistence(for num: Int) -> Int {
var number = num
var times = 0
while(String(number).characters.count != 1) {
var sum = 1
for c in String(number).characters {
sum *= Int("\(c)")!
}
number = sum
print(sum)
times += 1
}
return times
}
Best Practices
func persistence(for num: Int) -> Int {
let digits: [Int] = String(num).characters.flatMap { Int(String($0)) }
return digits.count == 1 ? 0 : 1 + persistence(for: digits.reduce(1, *))
}
Summary
reduce方法;
flatMap方法;
递归思想
Multiples of 3 and 5
Instructions
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
- Note: If the number is a multiple of both 3 and 5, only count it once.
My Submit
func solution(_ num: Int) -> Int {
if num >= 3 {
var sum = 0
for i in 3..<num {
if i % 3 == 0 || i % 5 == 0 {
sum += i
continue
}
}
return sum
}
return 0
}
Best Practice
func solution(_ num: Int) -> Int {
var sum = 0
for i in 0..<num {
if (i % 3 == 0 || i % 5 == 0) {
sum += i
}
}
return sum
}
Summary
很简单的一个判断求和的题目,额外判断了入参小于三的情况,正常做题是不需要考虑的,算是习惯吧