LeetCode66 Plus One

题目:

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.(Easy)

分析:

基本的加法操作,用carry处理进位即可,注意最后多一位的时候insert一个1。

代码:

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int>& digits) {
 4         int carry = 0;
 5         digits[digits.size() - 1]++;
 6         for (int i = digits.size() - 1; i >= 0; --i) {
 7             int temp = digits[i] + carry;
 8             if (temp == 10) {
 9                 carry = 1;
10                 temp = 0;
11             }
12             else {
13                 carry = 0;
14             }
15             digits[i] = temp;
16         }
17         if (carry == 1) {
18             digits.insert(digits.begin(), 1);
19         }
20         return digits;
21     }
22 };
时间: 2025-01-04 08:49:18

LeetCode66 Plus One的相关文章

LeetCode66/169/79 Plus One/Majority Element /Word Search

一: Plus One 题目: 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. 链接:https://leetcode.com/problems/plus-one/ 分析:就是简单的加法运算,注意进位

LeetCode66.加一

给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一. 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字. 你可以假设除了整数 0 之外,这个整数不会以零开头. 示例 1: 输入: [1,2,3] 输出: [1,2,4] 解释: 输入数组表示数字 123. 示例 2: 输入: [4,3,2,1] 输出: [4,3,2,2] 解释: 输入数组表示数字 4321. class Solution { public int[] plusOne(int[] digits) { if

LeetCode日记3

(2015/11/3) LeetCode-36 Valid Sudoku:(easy) 1)使用数据结构 set<char> emptyset; vector<set<char>> mp(27, emptyset); 2)下标0-8存储行中的数字,9-17存储列中的数字,18-26存储3×3块中数字. 3)双重for循环中,i表示行,9 + j表示列,18 + i / 3 + 3 * (j / 3)表示块. (2015/11/12) LeetCode-38 Count

20191230-20200102总结(1)

LeetCode66. Plus One - Easy LeetCode67. Add Binary - Easy LeetCode69. Sqrt(x) - Easy 二分找 LeetCode70. Climbing Stairs - Easy dp LeetCode71. Simplify Path - Medium Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert