LeetCode 2162. 设置时间的最少代价

思路

模拟枚举所有情况。
四位数字,小时和分钟最大为99。
一个分钟数小于40的时间有两种表示方式,小时数减1(大于等于1小时),分钟数加60。
例如:时间99 seconds。

1
99

或者

1
139

最后就是如果小时数为100,处理成99

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
int getNum(int h,int m){
return h*100+m;
}
int getLen(int n){
int res=0;
while(n){
res++;
n/=10;
}
return res;
}
int calNum(int startAt,int moveCost,int pushCost,int t,int l){
int res=0;
int curNum=startAt;
int i=1;
while(l>=i){
int curN=t/int(pow(10,l-i))%10;
if(curN!=curNum){
res+=moveCost;
curNum=curN;
}
res+=pushCost;
i++;
}
return res;
}
int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) {
int h=targetSeconds/60;
int m=targetSeconds%60;
if(h>99){
m+=60*(h-99);
h=99;
}
int t=getNum(h,m);
int l=getLen(t);
int res=calNum(startAt,moveCost,pushCost,t,l);
if(m+60<100&&h>0){
h--,m+=60;
t=getNum(h,m);
l=getLen(t);
res=min(res,calNum(startAt,moveCost,pushCost,t,l));
}
return res;
}
};

参考


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!