1342. 将数字变成 0 的操作次数【简单题】【每日一题】
思路:【模拟】
- 定义计数变量ans=0;
- 当num>0时,如果num是偶数,就将其除2,如果是奇数,就将其减1;每次操作ans加1。
- 最后返回ans。
代码:
class Solution {
public int numberOfSteps(int num) {
int ans = 0;
while (num>0){
if (num % 2 == 0){
num /= 2;
}else {
num--;
}
ans++;
}
return ans;
}
}
1507. 转变日期格式
思路:【打表】
- 打表直接冲就完了。
代码:
class Solution {
public String reformatDate(String date) {
String[] days = {"1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13th","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st"};
Map<String ,String > months = new HashMap<String ,String >(){
{
put("Jan","01");
put("Feb","02");
put("Mar","03");
put("Apr","04");
put("May","05");
put("Jun","06");
put("Jul","07");
put("Aug","08");
put("Sep","09");
put("Oct","10");
put("Nov","11");
put("Dec","12");
}
};
StringBuilder sb = new StringBuilder();
String[] split = date.split(" ");
sb.append(split[2]);
sb.append("-");
sb.append(months.get(split[1]));
sb.append("-");
for (int i = 0; i < 31; i++) {
if (split[0].equals(days[i])){
if (i<9){
sb.append("0");
}
sb.append(i+1);
break;
}
}
return sb.toString();
}
}
用时对比:
农历2021最后一天,除夕快乐,新年快乐!
|