flutter 如何使用dart求解,给定一年,返回它所处的世纪

mkshixfv  于 2022-11-30  发布在  Flutter
关注(0)|答案(2)|浏览(125)

给定一个年份,返回该年份所在的世纪。第一个世纪从1年到100年(含),第二个世纪从101年到200年(含),依此类推。

Example

For year = 1905, the output should be
solution(year) = 20;
For year = 1700, the output should be
solution(year) = 17.
Input/Output

[execution time limit] 4 seconds (dart)

[input] integer year

A positive integer, designating the year.

Guaranteed constraints:
1 ≤ year ≤ 2005.

[output] integer

The number of the century the year is in.
jum4pzuy

jum4pzuy1#

int getCentury(int year) => (year - 1) ~/ 100 + 1;
vngu2lb8

vngu2lb82#

这就是你想要吗?

void main() {
   
  int year1 = 1905;
  int year2 = 1700;
  print('year1 : ${getCentury(year1)}');   //20
  print('year2 : ${getCentury(year2)}');   //17
}

int getCentury(int year){
  if(1 > year || 2005 < year){
    return 0;
  }
  
  int century = year ~/ 100;
  int temp = year % 100;
  
  if(temp != 0){
    century += 1;
  }
  
  return century;
}

相关问题