Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
题目:一眼看去,纯数字+,加到个位数。。
思路:按照之前实现加法运算那一套,我思考良久,这个怕是要用到逻辑运算吧,与或非异或同或...而后进行了长时间的纸上演算未果,开始怀疑智商,忍不住去网上一路搜索之,知道看到这样一串数字123456789123456....恍然醒悟,管你哪个最后按照规则运算一番都是有规律的,什么规律呢,看你整除9余啥,于是,以下:
public int addDigits(int num) {
return (num-1)%9+1;
}
感觉此类题跟我妹妹做的奥赛题一样的,你也没思路,也没办法,就是找规律.....