codewars--js--Human Readable Time—Math对象,parseInt()

问题描述:

Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)

  • HH = hours, padded to 2 digits, range: 00 - 99
  • MM = minutes, padded to 2 digits, range: 00 - 59
  • SS = seconds, padded to 2 digits, range: 00 - 59

The maximum time never exceeds 359999 (99:59:59)

You can find some examples in the test fixtures.

我的答案:

 1 function humanReadable(seconds) {
 2   // TODO 
 3   var HH=0;MM=0;SS=0;
 4   if(seconds>359999){return false;}
 5     HH=parseInt(seconds/3600);
 6     MM=parseInt((seconds-HH*3600)/60);
 7     SS=parseInt((seconds-HH*3600)%60);
 8     HH=(HH<10)?"0"+HH:HH;
 9     MM=(MM<10)?"0"+MM:MM;
10     SS=(SS<10)?"0"+SS:SS;
11     return (HH+":"+MM+":"+SS).toString();      
12 }

优秀答案:

1 function humanReadable(seconds) {
2   var pad = function(x) { return (x < 10) ? "0"+x : x; }
3   return pad(parseInt(seconds / (60*60))) + ":" +
4          pad(parseInt(seconds / 60 % 60)) + ":" +
5          pad(seconds % 60)
6 }

js取整取余

http://www.jb51.net/article/50005.htm

方法 含义 结果
parseInt(5/2); 丢弃小数部分,保留整数部分 2
Math.ceil(5/2); 向上取整,有小数就整数部分+1 3
Math.round(5/2); 四舍五入 3
Math.floor(5/2); 向下取整 2

1,转换函数(对String类型有效,否则就是NoN)

parseInt() //把字符串转换成整数    

parseInt("123blue"); //return 123

parseInt("22.5"); //return 22

parseFloat() //把字符串转换成浮点数

parseFloat("1234blue");  //return 1234.0

parseFloat("22.5"); //return 22.5

2,强制类型转换

Boolean(value)----把给定的值转换成Boolean型

当要转换的值是至少有一个字符的字符串、非0数字或对象(下一节将讨论这一点)时,Boolean()函数将返回true。如果该值是空字符串、数字0、undefined或null,它将返回false。

Number(value)----把给定的值转换成数字(可以是整数或浮点数)

String(value) ----把给定的值转成字符串

3,js的弱类型转换(只进行算术运算,实现了字符串到数字的类型转换)

var str="012.345";

x=x*1;   // return 数字12.345

4,其他常用的Math对象的方法

Math.abs(-1);  // 1

Math.log(1);  以e为底的对数,0

Math.max(1,2,3);  //3

Math.min(1,23);  //1

Math.random();  //返回0~1之间的随机数

Math.pow(2,3);  //2的3次方为8    

2的3次方: 2**3;

2的5次方: 2**5;

Math.sqrt(9,3); //8的平方根 为2

原文地址:https://www.cnblogs.com/hiluna/p/8719581.html