【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
代码
//点击指定元素
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();
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
语法那很好改。不知道也没事?直接拿你的代码附上报错问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 ->
% | ^
)
【LeetCode2180】[Go/C++/C#/Ruby/Swift/Kotlin/Rust/PHP/TS/Racket/Dart/Java/Elixir/Scala/Erlang] 统计各位数字之和为偶数的整数个数的更多相关文章
- 【转】Android世界的Swift - Kotlin语言
最近Oracle又在和Google撕的厉害,才知道还有这么Kotlin在Android像Swift在Mac的地位一说. Kotlin是一门与Swift类似的静态类型JVM语言,由JetBrains设计 ...
- Android平台的Swift—Kotlin
WeTest 导读 Kotlin 已经出来较长一段时间了,有些同学已经对Kotlin进行了深入的学习,甚至已经运用到了自己的项目当中,但是还有较多同学可能只是听过Kotlin或简单了解过,这篇文章的目 ...
- Swift语言中与C/C++和Java不同的语法(一)
---恢复内容开始--- Swift作为苹果官方推出的IOS开发的推荐语言,在过去的几年间受到了越来越广泛的关注,其实编程的人都知道,不同的编程语言大同小异,掌握一门新的语言关键是了解它与其它语言不同 ...
- Swift语言中与C/C++和Java不同的语法(二)
这一部分,主要讲Swift中创新的可选型(optionals) 一.概要 可选型是Swift创新的一种新的类型,首先看一下可选型的应用场景: var errorCode : Int = 404 这时候 ...
- Swift语言中与C/C++和Java不同的语法(五)
这一节将会提到Swift中其他的关于函数的应用,这些内容包括有: 默认参数值和可变参数值.常量参数.返回函数类型和函数嵌套: 一.默认参数值和可变参数值 对默认参数值是指在函数的声明中就已经定义了参数 ...
- Swift语言中与C/C++和Java不同的语法(四)
这一节,我们将会讨论一下Swift中的函数相关的基本内容 首先是函数的创建: func sayHello (name:String) -> String { return "Hello ...
- Swift语言中与C/C++和Java不同的语法(三)
这一部分的主要内容是Swift中的Collections 我们知道Java中的Collection基本上是每一个Java程序猿接触到的第一个重要的知识点. 在Swift中也不例外,Swift中的Col ...
- Java & Groovy & Scala & Kotlin - 20.Switch 与模式匹配
Overview 本章主要介绍高级条件语句中的 switch 语句以及其增强版的模式匹配. Java 篇 Switch 特点 Java 中 switch 语句功能类似 if,但是 switch 主要用 ...
- gradle 混合编程java、scala、kotlin、groovy
众所周知,java是基于JVM的开发语言,但能够在JVM上运行的开发语言不仅仅有java,目前还有很热门的kotlin(kotlin不仅仅只能开发Android).scala.groovy等等.目前国 ...
- [Swift]LeetCode129. 求根到叶子节点数字之和 | Sum Root to Leaf Numbers
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...
随机推荐
- 「SOL」射命丸文的笔记 (洛谷)
讲题人:"这是一个很经典的模型,大家应该都会" 我:"???" # 题面 给出 \(m\),求所有 \(m\) 个点的有标号强联通竞赛图的哈密顿回路数量的平均数 ...
- 解决eclipse创建动态Web项目没有Web->Dynamic Web Project问题
有时候在eclipse新建Dynamic Web Project,File->New->Other->Web并没有发现Dynamic Web Project选项如下图:(那也不要慌解 ...
- 解决通过Eclipse启动Tomcat-Run On Server出现The selection cannot be run on any server
有时候通过Eclipse启动Tomcat-Run On Server会出现The selection cannot be run on any server的情况如下图: 这是因为没有在eclipse ...
- iOS用runtime给一个类动态添加方法 ---class_addMethod
先介绍下class_addMethod这个fangfa /** * Adds a new method to a class with a given name and implementat ...
- Win10解决无法访问其他机器共享的问题【转】
你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问.这些策略可帮助保护你的电脑免受网络上不安全设备或恶意设备的威胁.管理员身份执行sc.exe config lanmanworks ...
- Ubuntu16.04配置网卡
设置步骤: 1.路由器插电后,电脑使用网线,连接无线路由器任一LAN口,注意两者单独连接,先不要连接宽带网线.打开电脑浏览器,在地址栏输入192.168.100.1. 在路由器的管理界面,输入路由器的 ...
- oracle函数及相关问题
show user 查看当前用户select * from tab: 查看当前数据库中的表desc 表名 : 查看表结构 between and 包含开头结尾 函数: months_between(a ...
- tex基础
Tex中输入空格以及换行 1. 使用\ 表示空格以及调整空格的大小quad空格 a \qquad b 两个m的宽度quad空格 a \quad b 一个m的宽度 ...
- 循环结构(Java)
基本介绍 while循环语法 while(布尔表达式){循环内容} 只要布尔表达式为true,循环则会一直循环下去 我们大多数会让循环停止下来,我们需要一个让表达式失效的方式来结束循环 少部分需要循环 ...
- Spring系列之基于注解的容器配置7
目录 基于注解的容器配置 @Required(弃用) `@Autowired` `@Primary` @Qualifier 使用泛型作为自动装配限定符 `@Resource` `@Value` 使用` ...