题目:输入“hh:mm:ss”,将字符串时间,转化为秒数
解题步骤:
- 将输入的字符串
“hh:mm:ss”
使用split()
函数进行分隔,分隔后为["hh","mm","ss"]
- 再分别把分隔出来的数组进行分别赋值给
h
,m
,s
,并进行数字转化 - 再把所以转化的秒数进行相加,并输出结果
注:python可使用int()
函数进行数字转化,而typescript需要使用parseInt()
函数进行数字转化
使用Python语言:
def time_transformation(str):
"""
字符串时分秒转换成秒
"""
h, m, s = str.strip().split(':') # .split()函数将其通过':'分隔开,.strip()函数用来除去空格
time = int(h) * 3600 + int(m) * 60 + int(s) # int()函数转换成整数运算
print(time)
return time
if __name__ == "__main__":
time_transformation("12:53:12")
使用TypeScript语言:
function timeTransformation(str:string) {
// 将输入的“hh:mm:ss”使用“:”进行分隔
let h = str.split(":")[0]
let m = str.split(":")[1]
let s = str.split(":")[2]
// 将字符串转化为数字
let hour = parseInt(h) * 3600
let minute = parseInt(m) * 60
let second = parseInt(s)
// 将时分秒转化的秒数相加
let time = hour + minute + second
console.log(time)
return time
}
timeTransformation("12:53:12")
使用Go语言
由于GO语言的字符村转化相对复杂,所以此处我使用的是第三方库 cast
库进行字符转换
package main
import (
"fmt"
"strings"
"github.com/spf13/cast"
)
// 字符串时分秒转换成秒
func main() {
fmt.Println(times("15:15:15"))
}
func times(s string) int {
// 使用Split()函数,根据 “:” 进行字符分割,并依次赋值给变量
segmentation := strings.Split(s, ":")
hour := segmentation[0]
minute := segmentation[1]
second := segmentation[2]
// 使用第三方库 cast 进行整型转换
hours := cast.ToInt(hour)
minutes := cast.ToInt(minute)
seconds := cast.ToInt(second)
sum := hours*3600 + minutes*60 + seconds
return sum
}
使用Java语言
import java.util.ArrayList;
import java.util.List;
public class Test_Interview {
public static void main(String[] args)
{
System.out.println(times("15:15:15"));
}
public static int times(String str) {
// 使用split()函数分割字符串
var split = str.split(":");
// 创建列表
List<Integer> myList = new ArrayList<>();
// 循环分割的字符串,添加进列表中
for (String data: split)
myList.add(Integer.valueOf(data));
// 根据索引获取数据
var hour = myList.get(0);
var minute = myList.get(1);
var second = myList.get(2);
var sum = (hour * 3600) + (minute * 60) + second;
return sum;
}
}
注:要是觉得文章写得不错,记得留个赞哦!