找LeetCode上简单的题目来撑过30天啦(DAY2)

我完蛋了~明天要上班呢~下班还要出趟远门,结果拚一点进度拚到现在,太久没写程序,语法忘光光罗,第一个礼拜大概都会是写EASY抓一下语法吧/images/emoticon/emoticon01.gif

以下是今天的重点?
题号:258. 标题:Add Digits 难度:easy
题目内容
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Example 1:
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
Example 2:
Input: num = 0
Output: 0

Constraints:
• 0 <= num <= 231 - 1

Follow up: Could you do it without any loop/recursion in O(1) runtime?

我的程序

class Solution {
    public int addDigits(int num) {
        String temp ;
        int i,tnum=0;
        if(Integer.toString(num).length()==1){
                return num;
            }
                while(Integer.toString(num).length()>1){
                temp =  Integer.toString(num);
                for(i=0;i<Integer.toString(num).length();i++){
                    tnum = tnum + Integer.parseInt(temp.substring(i,i+1)); 
                         } 
               num = tnum;
               tnum = 0; 
            if(Integer.toString(num).length()==1){
                return num;
           }
            
        }return num;   
    }
}

程序逻辑
依旧没什麽逻辑,就是把数字转字串,照题目逻辑一位一位转数字加起来,再去做判断,没什麽头脑的写法呢/images/emoticon/emoticon02.gif

此题花费较多的时间在
-sbustring()
String.substring(要抓的起始位置<包含>,抓的尾吧<不包含>)
如果是String a = "hello",substring(4,5) 就是o

-型态转换
Integer.toString(INT)数字转字串
Integer.parseInt(STRING)字串转数字

DAY2心得
我都写些解题纪录而已,没什麽值得参考的重点啦~然後我要来去洗洗睡了,没人看也是要跟大家说声,晚安!


<<:  Day 17 - 应用程序部署 - 浅谈 Rancher 的应用程序管理

>>:  [Day13] 多执行绪

Day46. 范例:摩斯电码 (解译器模式)

本文同步更新於blog 情境:让我们试着作一个摩斯电码机,它会将一般句子转成摩斯电码的表示 首先...

[2021铁人赛 Day04] General Skills 01

引言 今天我们就正式来解题吧! 就先从最基础的 General Skills 开始, 一边解题一边...

Day 20 ATT&CK for ICS - Evasion(2)

T0858 Change Operating Mode 如同Day15 ATT&CK for...

认识 C# 的 保留关键字

在C# 中包含所谓的 「保留关键宇」 ,就是C# 本身的指令名称, 不能用来宣告变数、常数、类别及方...

Day 46 (Node.js)

1.NPM版本 无须更新到最新,怕错误 2.制作专案package.json npm init np...