[toc]
题解地址
https://leetcode.cn/problems/count-integers-with-even-digit-sum/solutions/2047123/by-yhm138_-w8co/ lc2180
代码
//点击指定元素
document.querySelector("#__next > div > div > div > div > div > div > div > div.shadow-level1.dark\\:shadow-dark-level1.flex.w-full.min-w-0.flex-col.rounded-xl.lc-lg\\:max-w-\\[700px\\].bg-layer-1.dark\\:bg-dark-layer-1 > div.relative.flex.w-full.flex-col > div.flex.w-full.flex-col.gap-4.px-5.pt-4.pb-8 > div.break-words > div > div > div > div.flex.select-none.bg-layer-2.dark\\:bg-dark-layer-2 > div:nth-child(13)").click();
//我的问题是,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++
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#
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
# @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
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
class Solution {
fun countEven(num: Int): Int {
return (1..num).count {
it.toString().toList().map { it.toInt() }.sum() % 2 == 0
}
}
}
//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
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
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
(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
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
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
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
object Solution {
def countEven(num: Int): Int = {
Range(1,num+1,1).count(x=>{
x.toString.toList.map(_.toInt).sum%2==0
});
}
}
%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)]).
思路
有些是拿适当的prompt问chatgpt写的。
有一些tips:
-
chatgpt是真的强,没人比chatgpt更懂FP :-p
-
chatgpt分不清不同语言的
Range/range
是左闭右开还是左闭右闭。没事,人类也记不住。 -
写
elixir
的时候,chatgpt给出的答案中,匿名函数fn
没有和end
配对。你如果知道基础的elixir
语法那很好改。 -
不知道也没事?直接拿你的代码附上报错直接问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 ->
% | ^
)
标签:count,Java,Scala,int,sum,num,return,div,Erlang From: https://www.cnblogs.com/yhm138/p/17029417.html