leetcode| Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.git

For example:code

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.it

題目:一眼看去,純數字+,加到個位數。。搜索

思路:按照以前實現加法運算那一套,我思考良久,這個怕是要用到邏輯運算吧,與或非異或同或...然後進行了長時間的紙上演算未果,開始懷疑智商,忍不住去網上一路搜索之,知道看到這樣一串數字123456789123456....恍然醒悟,管你哪一個最後按照規則運算一番都是有規律的,什麼規律呢,看你整除9餘啥,因而,如下:di

public int addDigits(int num) {
  return (num-1)%9+1;
}時間

感受此類題跟我妹妹作的奧賽題同樣的,你也沒思路,也沒辦法,就是找規律.....思考

相關文章
相關標籤/搜索