当前位置:网站首页>leetcode-aboutString
leetcode-aboutString
2022-07-26 05:39:00 【Codestars codestars】
About string operations

The most classic must be this problem : String addition
Ideas : At first, I saw the requirements of the topic , You cannot convert the input string directly into numbers . Then I thought , Since I'm not allowed to use it , Then I'll write one myself .
public int stringToInt(String num1) {
int total=0;
int length=num1.length();
for(int i=0;i<length;i++){
total+=(num1.charAt(i)-'0')*Math.pow(10,length-i-1);
}
return total;
}
So I wrote a string turn int Function of , I intend to convert two numbers into int Perform the add operation . Then we get the addend int.
At this point, you should int Turn into String, After thinking for a long time, I don't know how to turn , Then I read the answer , Discovery can :
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append("");
stringBuffer.append(addnum);
Build a stringBuffer,append(“”), Then you can append(int)
You can output .
I thought it was perfect , But there is a problem , This is the case where overflow occurs !!!
If two numbers are very big , For example, the following situation :
Well, the two one. int The sum has actually exceeded int What can be expressed , So it will overflow , At this time int It is not the result of adding two real numbers , And we will int Transformed string Certainly not the real result .
So this plan is not feasible
In order not to overflow the results , We cannot turn it into int Add up , You have to use strings , Every bit adds up , such ( character string ) There is no overflow .
StringBuffer result=new StringBuffer();
result.append("");
int tag1=num1.length()-1;
int tag2=num2.length()-1;
int tagResult1=0;
int tagResult2=0;
int sum=0;
int carry=0;
while(tag1>=0||tag2>=0){
if(tag1<0){
tagResult1='0';
}else{
tagResult1=num1.charAt(tag1);
}
if(tag2<0){
tagResult2='0';
}else{
tagResult2=num2.charAt(tag2);
}
sum=tagResult1-'0'+tagResult2-'0'+carry;
result.append(sum%10);
// Direct will carry as sum/10 There is no need to judge whether it is greater than 10, Do you need to carry ,carry It can already be shown
carry=sum/10;
tag1--;
tag2--;
//999+1 This is just right 000 Then enter a situation
if(tag1<0&&tag2<0&&carry==1){
result.append(1);
}
}
return result.reverse().toString();
This code is smelly and long , To simplify the :
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
StringBuffer ans = new StringBuffer();
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1.charAt(i) - '0' : 0;
int y = j >= 0 ? num2.charAt(j) - '0' : 0;
int result = x + y + add;
ans.append(result % 10);
add = result / 10;
i--;
j--;
}
ans.reverse();
return ans.toString();
String multiplication
Ideas :
leetcode Big guy thinking :
Code :
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
//Multiply Strings Similarly, it cannot be directly transformed into int Multiply , Because the data is too large , The result will overflow
// So we still need to use the idea of string addition
// character string 123 *456 It's actually 6*123+50*123+400*123 ( The addition here uses the string addition we have written )
// and 6*123 This multiplication , It's not difficult. , It is also the idea of addition , Multiply sequentially , And then carry
String res=new String();
for(int i = num1.length() - 1 ; i >= 0; i--){
int mul = (num1.charAt(i) - '0');
StringBuffer str=new StringBuffer();
int sum = 0,add = 0;
for(int j = num2.length() - 1;j >= 0; j--){
sum=mul*(num2.charAt(j)-'0')+add;
str.append(sum%10);
add=sum/10;
//!!!!!
// Here, too ! Multiplication also has overflow !!!
if(j == 0 && add != 0){
str.append(add % 10);
}
}
str.reverse();
for(int k=i;k < num1.length() - 1; k++){
str.append(0);
}
res=addStrings(res,str.toString());
}
return res;
}
public String addStrings(String num1, String num2) {
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
StringBuffer ans = new StringBuffer();
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1.charAt(i) - '0' : 0;
int y = j >= 0 ? num2.charAt(j) - '0' : 0;
int result = x + y + add;
ans.append(result % 10);
add = result / 10;
i--;
j--;
}
ans.reverse();
return ans.toString();
}
}
Also attached is the solution of the great God :

class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
int[] res = new int[num1.length() + num2.length()];
for (int i = num1.length() - 1; i >= 0; i--) {
int n1 = num1.charAt(i) - '0';
for (int j = num2.length() - 1; j >= 0; j--) {
int n2 = num2.charAt(j) - '0';
int sum = (res[i + j + 1] + n1 * n2);
res[i + j + 1] = sum % 10;
res[i + j] += sum / 10;
}
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < res.length; i++) {
if (i == 0 && res[i] == 0) continue;
result.append(res[i]);
}
return result.toString();
}
}
author :breezean
link :https://leetcode.cn/problems/multiply-strings/solution/you-hua-ban-shu-shi-da-bai-994-by-breezean/
source : Power button (LeetCode)
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .
边栏推荐
- 动态内存管理及柔性数组
- If MySQL calculates the current month change / current month increase / year-on-year change / year-on-year increase?
- Redis persistence AOF
- MongonDB API使用
- 轻量级单片机命令行交互项目,全部开源
- Embedded development notes, practical knowledge sharing
- You'd better not take this kind of project!
- Common modules in ansible
- Lightweight MCU command line interaction project, all open source
- Benji Banas launched the second season of earn while playing bonus activities, supporting the use of multiple Benji passes!
猜你喜欢

A trick to teach you to easily understand Potter's map

FPGA question brushing sequence detection

Qt编写物联网管理平台47-通用数据库设置

IVR在voip电话系统的应用与价值
C language explanation series - understanding of functions (4) declaration and definition of functions, simple exercises

如何从内存解析的角度理解“数组名实质是一个地址”?

No background, no education? Is it really hopeless for specialist testers to enter Internet factories?
![[personal summary] end of July 24, 2022](/img/9e/dfc37c2684aa8849291817782c947b.png)
[personal summary] end of July 24, 2022

【STM32系列汇总】博主的STM32实战快速进阶之路(持续更新)

动态内存管理及柔性数组
随机推荐
Who is responsible for the problems of virtual idol endorsement products? And listen to the lawyer's analysis
TZC 1283: simple sort Bubble Sort
Rocbossphp free open source light community system
Use of feign (Part 2)
高频电子线路复习考试题及答案
Chapter 2 - getting started
MySQL optimization
Mongodb common commands
YOLOV3预备工作
Go exceed API source code reading (VI) -- deletesheet (sheet string)
Home VR panoramic display production to improve customer transformation
Hack The Box - Introduction to Networking Module详细讲解中文教程
电机控制专栏文章汇总
How can red star Macalline design cloud upgrade the traditional home furnishing industry in ten minutes to produce film and television level interior design effects
Introduction to Chinese text error correction task
FTP实验及概述
I also found excellent software and hardware projects, all open source
How students apply for free idea
[论文笔记] 面向网络语音隐写的抗分组丢失联合编码
no networks found in /etc/cni/net.d
