【LeetCode2180】[Go/C++/C#/Ruby/Swift/Kotlin/Rust/PHP/TS/Racket/Dart/Java/Elixir/Scala/Erlang] 统计各位数字之和为偶数的整数个数
题解地址
https://leetcode.cn/problems/count-integers-with-even-digit-sum/solutions/2047123/by-yhm138_-w8co/ lc2180
脚本分享
LeetCode题解区域的代码编辑器(Markdown)支持这样的语法:分tab展示不同编程语言的代码
但是如果达到大概15个tab时,底部并没有出现水平滚动条,不方便用户查看。
我写了个脚本,添加了水平滚动条来解决这个问题。
代码
golang
//我的问题是,Go支持函数式编程吗?
func countEven(num int) int {
a := makeRange(1, num)
evenCount := len(filter(a, func(num int) bool {
numStr := strconv.Itoa(num)
digits := strings.Split(numStr, "")
mySum:=0
for _,ele :=range digits{
d, _ := strconv.Atoi(ele)
mySum=mySum+d
}
return mySum%2 == 0
}))
return evenCount
}
func filter(src []int, p func(int) bool) []int {
dst := []int{}
for _, s := range src {
if p(s) {
dst = append(dst, s)
}
}
return dst
}
func makeRange(min, max int) []int {
a := make([]int, max-min+1)
for i := range a {
a[i] = min + i
}
return a
}
c++
//C++
class Solution {
public:
int countEven(int num) {
std::vector<int> range(num);
std::iota(range.begin(), range.end(), 1);
return std::count_if(range.begin(), range.end(), [](int x) {
std::string str = std::to_string(x);
return std::accumulate(str.begin(), str.end(), 0, [](int sum, char c) {
return sum + (c - '0');
}) % 2 == 0;
});
}
};
C#
//C#
using System;
using System.Linq;
public class Solution {
public int CountEven(int num) {
return Enumerable.Range(1, num).Count(x => x.ToString().Select(c => c - '0').Sum() % 2 == 0);
}
}
ruby
# ruby
# @param {Integer} num
# @return {Integer}
def count_even(num)
(1..num).count { |x| x.to_s.chars.map(&:to_i).sum % 2 == 0 }
end
swift
//swift
class Solution {
func countEven(_ num: Int) -> Int {
return (1...num).filter { x in
x.description.map { Int(String($0))! }.reduce(0, +) % 2 == 0
}.count
}
}
kotlin
//kotlin
class Solution {
fun countEven(num: Int): Int {
return (1..num).count {
it.toString().toList().map { it.toInt() }.sum() % 2 == 0
}
}
}
rust
//rust
impl Solution {
pub fn count_even(num: i32) -> i32 {
(1..num+1).filter(|x| x.to_string().chars().map(|c| c.to_digit(10).unwrap()).sum::<u32>() % 2 == 0)
.count() as i32
}
}
php
//php
class Solution {
/**
* @param Integer $num
* @return Integer
*/
function countEven($num) {
$result = array_filter(range(1, $num), function($x) {
$sum = 0;
foreach(str_split((string)$x) as $digit) {
$sum += intval($digit);
}
return $sum % 2 == 0;
});
return count($result);
}
}
typescript
//typescript
function countEven(num: number): number {
return Array.from(Array(num).keys())
.map(x => x + 1)
.filter(x => x.toString()
.split('')
.map(Number)
.reduce((a, b) => a + b, 0) % 2 === 0)
.length;
}
racket
;racket
(define/contract (count-even num)
(-> exact-integer? exact-integer?)
(length
(filter (lambda (x)
(even? (apply + (map char->integer (string->list (number->string x))))))
(range 1 (add1 num))
)
)
)
dart
//dart
class Solution {
int countEven(int num) {
return Iterable.generate(num, (x) => x+1)
.where((x) =>
x.toString().split('').map(int.parse).reduce((a,b) => a+b) % 2 == 0
).length;
}
}
java
//java
import java.util.stream.IntStream;
public class Solution {
public static int countEven(int num) {
return (int) IntStream.range(1, num+1).filter(x ->
IntStream.range(0, String.valueOf(x).length())
.map(y -> Character.getNumericValue(String.valueOf(x).charAt(y)))
.sum() % 2 == 0
).count();
}
}
elixir
#elixir
defmodule Solution do
@spec count_even(num :: integer) :: integer
def count_even(num) do
(1..num)|>
Enum.count(fn x ->
x |> Integer.to_string() |> String.graphemes() |> Enum.map(&String.to_integer/1) |> Enum.sum() |> rem(2) == 0
end)
end
end
scala
//scala
object Solution {
def countEven(num: Int): Int = {
Range(1,num+1,1).count(x=>{
x.toString.toList.map(_.toInt).sum%2==0
});
}
}
erlang
%erlang
sum_digits(N) ->
sum_digits(N, 0).
sum_digits(0, Sum) -> Sum;
sum_digits(N, Sum) ->
sum_digits(N div 10, Sum + N rem 10).
-spec count_even(Num :: integer()) -> integer().
count_even(Num) ->
lists:foldl(fun(X, Acc) ->
Sum = sum_digits(X),
if Sum rem 2 == 0 ->
Acc + 1;
true ->
Acc
end
end,
0, [X || X <- lists:seq(1, Num)]).
性能
说实话你用上FP就别指望什么性能了。。。
Rust一如既往的优秀哈, 0 ms 2 MB
思路
题外话:如果要给{可读性,可维护性,代码长度,性能}排个序的话,应该是什么样的?
有些是拿适当的prompt问chatgpt写的。
有一些tips:
-
chatgpt是真的强,没人比chatgpt更懂FP :-p
-
chatgpt分不清不同语言的
Range/range
是左闭右开还是左闭右闭。没事,人类也记不住。 -
写
elixir
的时候,chatgpt给出的答案中,匿名函数fn
没有和end
配对。你如果知道基础的elixir
语法那很好改。 -
不知道你的erlang代码为什么错了?直接拿你的代码附上报错问chatgpt。
correct the erlang code
sum_digits(N) ->
sum_digits(N, 0).
sum_digits(0, Sum) -> Sum;
sum_digits(N, Sum) ->
sum_digits(N div 10, Sum + N rem 10).
-spec count_even(Num :: integer()) -> integer().
count_even(Num) ->
lists:foldl(fun(X, Acc) ->
if sum_digits(X) rem 2 == 0 ->
Acc + 1;
true ->
Acc
end
end,
0, [X || X <- lists:seq(1, Num)]).
Line 13: Char 24: call to local/imported function sum_digits/1 is illegal in guard
% 13| if sum_digits(X) rem 2 == 0 ->
% | ^