Problem
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
ExampleGiven [1,2,3] which represents 123, return [1,2,4].
Given [9,9,9] which represents 999, return [1,0,0,0].
Solution Update 2018-9class Solution { public int[] plusOne(int[] digits) { int n = digits.length; for (int i = n-1; i >= 0; i--) { if (digits[i] == 9) { digits[i] = 0; } else { digits[i]++; return digits; } } int[] res = new int[n+1]; res[0] = 1; return res; } }
進位法:
public class Solution { public int[] plusOne(int[] digits) { int carry = 1; for (int i = digits.length-1; i >= 0; i--) { int cur = digits[i] + carry; carry = cur / 10; digits[i] = cur % 10; if (carry == 0) break; } if (carry == 1) { int[] res = new int[digits.length+1]; res[0] = 1; return res; } return digits; } }
逢9化0法:
public class Solution { public int[] plusOne(int[] digits) { int last = digits.length-1; while (last >= 0 && digits[last] == 9) { digits[last] = 0; last--; } if (last == -1) { int[] res = new int[digits.length+1]; res[0] = 1; return res; } else { digits[last] += 1; return digits; } } }
文章版權歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/65564.html
Problem Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) ...
摘要:分析最后一次循環(huán)的時刻當與相差小于時,總是那么如果是,下一次直接跳出循環(huán),返回當與相差大于時,是,變成,如果是,循環(huán)結(jié)束的條件將是循環(huán)結(jié)束,返回 Problem The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case,...
摘要:使用,利用其按層次操作的性質(zhì),可以得到最優(yōu)解。這樣可以保證這一層被完全遍歷。每次循環(huán)取出的元素存為新的字符串。一旦找到和相同的字符串,就返回轉(zhuǎn)換序列長度操作層數(shù),即。 Problem Given two words (start and end), and a dictionary, find the length of shortest transformation sequence...
Problem There are a total of n courses you have to take, labeled from 0 to n - 1.Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed a...
摘要:方法上沒太多難點,先按所有區(qū)間的起點排序,然后用和兩個指針,如果有交集進行操作,否則向后移動。由于要求的,就對原數(shù)組直接進行操作了。時間復雜度是的時間。 Problem Given a collection of intervals, merge all overlapping intervals. Example Given intervals => merged intervals...
閱讀 3190·2021-11-10 11:35
閱讀 1295·2019-08-30 13:20
閱讀 1117·2019-08-29 16:18
閱讀 2131·2019-08-26 13:54
閱讀 2155·2019-08-26 13:50
閱讀 955·2019-08-26 13:39
閱讀 2473·2019-08-26 12:08
閱讀 1951·2019-08-26 10:37