【面试练习题】使用“暴力”的方法将字符串时间转化为秒数

该博客介绍了如何在不同编程语言中将字符串时间格式“hh:mm:ss”转换为秒数。涉及Python、TypeScript、Go和Java四种语言的实现方法,包括使用split()函数分隔字符串、数字转化和计算总秒数的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:输入“hh:mm:ss”,将字符串时间,转化为秒数

解题步骤:

  1. 将输入的字符串“hh:mm:ss”使用split()函数进行分隔,分隔后为["hh","mm","ss"]
  2. 再分别把分隔出来的数组进行分别赋值给hms,并进行数字转化
  3. 再把所以转化的秒数进行相加,并输出结果

注: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;  
    }
}

注:要是觉得文章写得不错,记得留个赞哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Warolitbos

如果有帮助,请我喝咖啡!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值