67. Add Binary Leetcode Python

【LeetCode·位运算.67】二进制求和,详解分析+两种思路+知识点总结 二进制求和 ????????开了一个专栏专门记录LeedCode题目,总结思路,分析题目,汇总知识点,熟能生巧!欢迎收藏! 一、题目 给你两个二进制字符串,返回它们的和(用二进制表示)。 输入为 非空 字符串且只包含数字 1 和 0。 示例 1: 输入: a = "11", b = "1" 输出: "100" 示例 2: 输入: a = "1010", b = "1011" 输出: "10101" 提示: 每个字符串仅由字符 ‘0’ 或 ‘1’ 组成 1 <= a.length, 阅读详情
For example,
a = "11"
b = "1"

Return "100".

这题的做法和前面一题plus one 一样,区别在于需要将两个string先相加,再判断是否要进位。

直接上代码吧。

class Solution:
    # @param a, a string
    # @param b, a string
    # @return a string
    def addBinary(self, a, b):
        a=list(a)
        b=list(b)
        for i in range(len(a)):
            a[i]=int(a[i])
        for i in range(len(b)):
            b[i]=int(b[i])
        lena=len(a)
        lenb=len(b)
        if lena<lenb:
            a,b=b,a
        itera=len(a)-1
        iterb=len(b)-1
        while itera>=0 and iterb>=0:
            a[itera]+=b[iterb]
            itera-=1
            iterb-=1
        for i in reversed(range(len(a))):
            digit=a[i]%2
            carry=a[i]/2
            a[i]=digit
            if i>0:
                a[i-1]+=carry
        if carry==1:
            a.insert(0,1)
        for i in range(len(a)):
            a[i]=str(a[i])
        return "".join(a)
                
        


保姆级教程:用Labelme标注车辆关键点,并一键转成YOLOv8-pose训练格式 本文提供了一份详细的车辆底盘关键点标注教程,从使用Labelme进行标注到一键转换为YOLOv8-pose训练格式的全流程指南。特别针对工业检测和自动驾驶场景,分享了标注规范、格式转换脚本及常见问题解决方案,帮助开发者高效准备训练数据并优化模型性能。 阅读详情

相关推荐

第三节: 串口通信(用CubeMX学习STM32)

用CubeMX学习STM32, 串口通信学习, 通过轮询方式和中断方式两种方式进行通信演示。 STM32F407zgt6

Kevin_8_Lee的博客 8911

leetcode67:二进制求和(python)

第二种方法的时间复杂度:空间复杂度:

weixin_56600336的博客 669

基于图神经网络的社交网络虚假账号检测系统 (Graph-based Fake Account Detection System, GFADS)

FOLLOWSRETWEETSSHAREDCOMMENTSLIKESMENTIONSUseruser_idusernamejoin_datebioavatar_urllocationverifiedis_fakeLOAD CSV这是决定模型性能的关键环节,需结合和。XXedge_indexy新账号缺乏历史数据和丰富关系。全网图可能包含数亿节点和数十亿边,难以直接训练。社交网络是动态变化的,虚假账号策略也在不断进化。获取大规模、高质量的真实/虚假账号标注数据非常困难。

Deng945201314的博客 1487

leetcode第67题python版二进制求和while遍历法

67. 二进制求和 给你两个二进制字符串,返回它们的和(用二进制表示)。输入为 非空 字符串且只包含数字 1 和 0。

前端帅小伙 549

”COMSOL“竟然如此简单!我悟了!!

COMSOL Multiphysics具有强大的多物理场全耦合仿真分析功能、高效的计算性能,可以保证数值仿真的高度精确,已被广泛应用于各个学科领域,近年来运用COMSOL来解决电化学实际工程问题也越来越普遍。

C1012562281的博客 3461

京东前端200道面试题及参考答案(中)

前端优化是“提升用户体验、降低资源消耗”的核心手段,需围绕“用户感知的性能指标”(如页面加载速度、交互流畅度)展开,覆盖加载优化、渲染优化、代码优化、网络优化、缓存优化、性能监控六大维度,每个维度下有具体可落地的措施,同时需结合项目实际场景(如单页应用、电商首页)选择优化方案。分页组件需通过props接收“数据总量、当前页、每页条数”等基础信息,通过emit触发“页码切换、每页条数变化”的回调(供父组件请求对应页数据),同时定义默认值确保兼容性。核心Props与Emit设计<template>

大模型大数据攻城狮的专栏 597

python LeetCode 刷题记录 67

进制转换

weixin_46483785的博客 331

2026 AI Agent Harness Engineering 生态报告:开源工具链的现状与未来趋势

IEEE P2863-2025《通用人工智能自主代理技术架构与评估规范》于2025年11月正式发布,将AI Agent(通用人工智能自主代理)定义为:一种具备感知(Perception)、记忆(Memory)、推理(Reasoning)、规划(Planning)、行动(Action)五大核心能力闭环,能够在无显式指令覆盖全部环节的前提下,自主完成特定领域或开放领域复杂任务的智能实体。

AI 算法实战派 503

LeetCode刷题(python版)——Topic67. 二进制求和

给你两个二进制字符串a和b,以二进制字符串的形式返回它们的和。

weixin_54039182的博客 679

【Android性能优化】Android App 冻结与内存压缩:CachedAppOptimizer 源码级解析

本文基于 AOSP Android 16 源码,以 `CachedAppOptimizer` 为核心,深度解析 Android 对"后台缓存应用"的两大治理手段——**进程冻结(Freezer)**与**内存压缩(Compaction)**。文中完整还原冻结的 debounce 去抖动机制、`mEarliestFreezableTime` 的最早可冻结时刻算法、粘性冻结(Sticky Freeze)的语义,以及解冻时必须"先解 binder 再解进程"的顺序奥义。

weixin_44081096的博客 203

社会网络仿真软件:NetLogo_(14).社会网络数据导入与导出

在NetLogo中,社会网络的仿真不仅依赖于模型的内部逻辑,还需要能够灵活地导入和导出数据。这使得用户可以利用外部数据来初始化模型,或者将模型的运行结果导出以便进一步分析。本节将详细介绍如何在NetLogo中实现社会网络数据的导入和导出,包括常见的数据格式和具体的代码示例。

kkchenjj的博客 602

leetcode 67. Add Binary Python快速实现

题目 leetcode 67. Add Binary Python 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...

2Dposeliu的博客 284

9篇3章3节:FAERS数据库公共仪表板搜索功能操作与解析

FAERS(FDA不良事件报告系统)公共仪表板是一个强大的工具,用于查询和分析药物及生物制品的不良事件数据。通过该仪表板,用户可以按药品或不良反应进行搜索,查看报告数量、事件类型及时间分布,从而辅助药物安全性分析和科研研究。本文重点介绍仪表板的搜索功能,包括按产品和按不良反应查询的操作步骤、筛选与多维数据分析方法,以及关键概念的解释,帮助用户科学、理性地使用FAERS数据,提升用药决策的准确性和安全性。

MD Code 1600

[leetcode] 67. Add Binary @ python

原题 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” Exampl...

闲庭信步 316

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

LeetCode之 67. Add Binary python

给定两个二进制字符串,返回他们的和(用二进制表示)。输入为非空字符串且只包含数字 1 和 0。示例 1:输入: a = "11", b = "1" 输出: "100"示例 2:输入: a = "1010", b = "1011" 输出: "10101"class Solution(object): def addBinary(self, a, b): "&

新雪兰 294

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

LeetCode 67 — Add Binary(C++ Java Python)

题目:http://oj.leetcode.com/problems/add-binary/ Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". 题目翻译: 给定两个二进制字符串,返回它们的和(也是一个二进制字符串)

龙之梦 3023

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

leetcode python3 简单题67. Add Binary

1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第六十七题 (1)题目 英文: Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only char...

从此做一个俗人 351

【LeetCode 67】Add Binary (Python)

Given two binary strings, return their sum (also a binary string). 题目分析:计算二进制数的加减法。 示例: a = “11” b = “1” Return “100”方法一:在写这篇博客前,我并不知道bin()这个方法。所以在这里给和我一样不了解的人科普一下。 bin() 返回一个整数 int 或者长整数 long in

Lucy_R的博客 467

LeetCode:67. Add Binary - Python

问题描述: 67. 二进制求和 给定两个二进制字符串,返回他们的和(用二进制表示)。 输入为非空字符串且只包含数字1和 0。 示例 1: 输入: a = “11”, b = “1” 输出: “100” 示例 2: 输入: a = “1010”, b = “1011” 输出: “10101” 问题分析: Python3实现: class Solution: def addBinary...

Growth Diary 661

【leetcode】67. Add Binary(Python & C++)

67. Add Binary题目链接67.1 题目描述:Given two binary strings, return their sum (also a binary string).For example,a = “11” b = “1” Return “100”.67.2 解题思路: 思路一:二进制相加的情况比较少,只有1、1和1、0和0、0,然后再加上是否进位就可以,所以可以直接列出所

I am what i am 1182

【LeetCode】67. Add Binary 解题报告(Python)

题目分析: 这一题让我们求二进制相加,给定两个由’0’,‘1’组成的字符串,返回相加的字符串,规则就是满二进一。由于有’11’,‘10001’这种两个串位数不同的情况,我们先把短的串前面填充0,让它的长度和长串相等,计算会比较方便,然后逐位相加,满二进一,保留进位符用于下一位相加。加到最后如果还有进位在最前面填充’1’。这一题与【LeetCode】66. Plus One 解题报告(Python)...

L141210113的专栏 355

python写算法题:leetcode: 67. Add Binary

class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ alen=len(a) blen=len(b) totallen=m...

189

[leetcode:python]67.Add Binary

题目: Given two binary strings, return their sum (also a binary string).For example, a = “11” b = “1” Return “100”.方法一:性能72msclass Solution(object): def addBinary(self, a, b): """

cyy2learn的博客 880

Leetcode 67. Add Binary (Python)

Given two binary stringsaandb, returntheir sum as a binary string. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" Constraints: 1 <= a.length, b.length <= 104 aandbconsi...

weixin_58080442的博客 955

[LeetCode By Python]67. Add Binary

题目: Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". 代码+调试: class Solution(object): def addBinary(self, a

sharonITlion的博客 224

LeetCode--Python解析【Add Binary】(67)

题目: 方法: class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ len_a = len(a) - 1 len_b = len(b) - 1 ...

ZJRN1027的博客 471
上一篇: Tripadvisor 面经解答 -持续更新ing
下一篇: 83. Remove Duplicates from Sorted List Leetcode Python
hyperbolechi
博客等级 码龄12年 7粉丝 178原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值