zoukankan      html  css  js  c++  java
  • leetcode 60-80 easy

    66、Plus One

    Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

    The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

    You may assume the integer does not contain any leading zero, except the number 0 itself.

    Example 1:

    Input: [1,2,3]
    Output: [1,2,4]
    Explanation: The array represents the integer 123.
    

    Example 2:

    Input: [4,3,2,1]
    Output: [4,3,2,2]
    Explanation: The array represents the integer 4321.

    C++

    class Solution {
    public:
        vector<int> plusOne(vector<int> &digits) {
            bool carry = true;
            
            for(int i=digits.size()-1; i >= 0 && carry; i--) {
                carry = (++digits[i]%=10) == 0;
            }
    
            if(carry) {
                digits.insert(digits.begin(), 1);
            }
        
            return digits;
        }
    };

    67. Add Binary

    Given two binary strings, return their sum (also a binary string).

    The input strings are both non-empty and contains only characters 1 or 0.

    Example 1:

    Input: a = "11", b = "1"
    Output: "100"

    Example 2:

    Input: a = "1010", b = "1011"
    Output: "10101"

    C++

    class Solution {
    public:
        string addBinary(string a, string b) {
             string s = "";
            
            int c = 0, i = a.size() - 1, j = b.size() - 1;
            while(i >= 0 || j >= 0 || c == 1)
            {
                c += i >= 0 ? a[i --] - '0' : 0;
                c += j >= 0 ? b[j --] - '0' : 0;
                s = char(c % 2 + '0') + s;
                c /= 2;
            }
            
            return s;
        }
    };
  • 相关阅读:
    用AutoHotkey实现 iThoughts 思维导图节点文本一键转到Excel
    AutoHotkey+BUG小狼毫+BUG win10输入法设置的艰难摸索(未完待续)
    什么时候用接口,什么时候用抽象类?
    Java接口
    单例设计模式和多例
    MySQL大小写
    SQL LIKE 操作符
    SQL DELETE 语句
    IDEA自动补全返回值类型的快捷键
    IDEA导入jar包
  • 原文地址:https://www.cnblogs.com/hotsnow/p/9595630.html
Copyright © 2011-2022 走看看