Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize string addition by Java

Shulou Source: shulou.com Published: 2022-06-01 11:24:33 09月14日 Update

This article mainly explains "Java how to achieve string addition", the article explains the content is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "Java how to achieve string addition" bar!

Topic: the addition of two strings representing binary numbers

Train of thought: add up from the low position, every two into one:

For example: string a = "100", a [2] is "0";-record the rounding of the sum with a variable. > Language:cpp

Class Solution {public:string addBinary (string a, string b) {string s = ""; / / I the index value of string a, the index value of j string b int c = 0, I = a.size ()-1, j = b.size ()-1 strike / strings an and b are not traversed, or there is carry, continue to calculate while (I > = 0 | | j > = 0 | c = = 1) {/ / ternary operator: low sum c + = I > = 0? A [iMurt -] -'0': 0; c + = j > = 0? B [Jmurb -] -'0': 0 return return / result s = Korean (c% 2 +'0') + s beat / carry calculation c / = 2;} / / returns the result

Language:Python

Class Solution (object): def addBinary (self, a, b): ": type a: str: type b: str: rtype: str" if len (a) = 0: return bif len (b) = = 0: return aif a [- 1] = ='1' and b [- 1] = '1':return self.addBinary (self.addBinary (a [0:-1], b [0:-1])) '1') +' 0'if a [- 1] = ='0' and b [- 1] = '0':return self.addBinary (a [0:-1], b [0:-1]) +' 0'else:return self.addBinary (a [0:-1], b [0:-1]) +'1' thank you for your reading The above is the content of "how to achieve string addition in Java". After the study of this article, I believe you have a deeper understanding of how to achieve string addition in Java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Characters strings learning low bits content ideas situations indexes results two binary representatives variables that is numbers articles more knowledge knowledge points articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple MySQL OPPO Reno Microsoft macOS