iT邦幫忙

2021 iThome 鐵人賽

DAY 2
2
AI & Data

想到甚麼打甚麼系列 第 2

找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心得
我都寫些解題紀錄而已,沒什麼值得參考的重點啦~然後我要來去洗洗睡了,沒人看也是要跟大家說聲,晚安!


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY1)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY3)
系列文
想到甚麼打甚麼30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言