CodeSignal Arcade的题解,附原文和中文描述,可能会有多语言解

优先级: Ruby -> C++ -> Python3 -> 其他

本文覆盖Intro-> “The Journey Begins” 与 “Edge of the Ocean”

注意:中文描述非翻译,一般仅提取与解题相关信息


The Journey Begins

Three Problems in Total

Intro 的第一关

Prob1: Add

Write a function that returns the sum of two numbers.

中文描述:

编写一个返回两数字之和的函数

1
2
3
4
# ruby
def add(param1, param2)
  param1 + param2
end
1
2
3
4
// C++
int add(int param1, int param2) {
  return param1 + param2;
}
1
2
3
# Python3
def add(param1, param2): 
  return param1 + param2

Prob2: centuryFromYear

Given a year, return the century it str in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.

1 ≤ year ≤ 2005.

中文描述:

求出给定年份的所处的世纪,比如2001~2100是21世纪,而2000年是20世纪

年份大于等于1,小于等于2005

1
2
3
4
# ruby
def centuryFromYear(year)
  (year - 1) / 100 + 1
end
1
2
3
4
// C++
int centuryFromYear(int year) {
  return (year - 1) / 100 + 1;
}
1
2
3
# Python3
def centuryFromYear(year):
  return (year - 1) // 100 + 1

Prob3: checkPalindrome

Given the string, check if it str a palindrome.

A non-empty string consstrting of lowercase characters.

Palindrome: A palindrome str a string that reads the same left-to-right and right-to-left.

中文描述:

判断给定字符串是不是回文串

回文串是正读和反读都一样的字符串,比如 “HANNAH”, “asdsa”

注意:给出的是由小写字母组成的非空字符串

1
2
3
4
# ruby
def checkPalindrome(str)
  str == str.reverse
end
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// C++ Solution1
bool checkPalindrome(std::string str) {
  for (int i = 0; i < str.length() / 2; ++i)
    if (str[i] != str[str.length() - i - 1])
      return false;
  return true;
}

// C++ Solution2
// by chesia
bool checkPalindrome(string str) {
  return str == string(str.rbegin(),str.rend());
}
1
2
3
# Python3
def checkPalindrome(str):
  return str == str[::-1]

The Journey Begins 通过



Edge of the Ocean