以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。
以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。数据范围:
len(s),len(t)≤100000,字符串仅由'0'~‘9’构成
要求:时间复杂度 O(n)
示例1
输入:"1","99"
返回值:"100"
说明:1+99=100
求助大佬了!!! def sum_words(number1,number2):
return "".join(("'",str(int(number1) + int(number2)),"'"))
print(sum_words("1","99"))
'100' python爱好者. 发表于 2022-2-11 10:09
如果你不在意带不带双引号,只在意类型,可以这样写:
def sum_words(number1,number2):
return str(int(number1) + int(number2))
print(sum_words("1","99"))
100
你 type() 一下,两种方法都是字符串,只不过第一种有双引号! C/C++?
我最多可以做到时间复杂度:O(2n) 本帖最后由 jhq999 于 2022-2-11 18:28 编辑
复杂度O(2n) 除非可以用strlen,或者fscan,但这些函数里面也有循环
void StrAdd(char (* num))
{
int i=0,j=0,k=0;
while(num||num)
{
if (num)i++;
if(num)j++;
}
k=i>j?i:j+1;
while (i>-1||j>-1)
{
num+=(i<0?'0':num)+(j<0?'0':num);
if (num>105)
{
num-='9'+1;
num++;
}
else if(num)
{
num-='0';
}
i--,j--,k--;
}
num=num?'1':'0';
int cs=0;
}
int main()
{
char num={0};
scanf("%s%s",num,num);
StrAdd(num);
printf("%s",num);
return 0;
} 本帖最后由 jhq999 于 2022-2-12 00:08 编辑
int StrAdd(char (* num))
{
long long *a=(long long*)num,*b=(long long*)num,*c=(long long*)num;
*a=*a+*b;
int i=0;
while(num)
{
if(num>105)num+=1,num=num-106+'0';
else if(96<=num)num=num-96+'0';
else num=num+'0';
i++;
}
*c>>=8;
return i;
}
int main()
{
int i=0;
char num={0};
scanf("%s%s",num+1,num+1);
for (i = 1; i <4 ; i++)//小端倒放
{
num=num;
num=num;
num=num;
num=num;
num=num;
num=num;
}
num=num='\0';
while (!num)*(long long *)num>>=8;
while (!num)*(long long *)num>>=8;
i=StrAdd(num);
printf("%s",num+7-i);
return 0;
} 本帖最后由 傻眼貓咪 于 2022-2-12 00:10 编辑
#include <stdio.h>
#include <malloc.h>
typedef struct Node{
char c;
struct Node *next;
}Number;
int main()
{
Number *A = NULL, *B = NULL, *C = NULL, *tail;
char c;
int flag = 1, sum, r = 0;
while((c = getchar()) != '\n'){
if(c == ' '){
flag = 0;
continue;
}
if(flag){
tail = A;
A = (Number*)malloc(sizeof(Number));
A->c = c;
A->next = tail;
}
else{
tail = B;
B = (Number*)malloc(sizeof(Number));
B->c = c;
B->next = tail;
}
}
while(A || B || r){
Number *p = A;
Number *q = B;
tail = C;
C = (Number*)malloc(sizeof(Number));
if(A && B){
sum = (A->c - '0') + (B->c - '0') + r;
c = sum%10 + '0';
r = sum/10;
C->c = c;
A = A->next;
B = B->next;
}
else if(A){
sum = (A->c - '0') + r;
c = sum%10 + '0';
r = sum/10;
C->c = c;
A = A->next;
}
else if(B){
sum = (B->c - '0') + r;
c = sum%10 + '0';
r = sum/10;
C->c = c;
B = B->next;
}
else if(r){
C->c = r + '0';
r = 0;
}
C->next = tail;
free(p);
free(q);
}
while(C){
printf("%c", C->c);
Number *p = C;
C = C->next;
free(p);
}
free(A);
free(B);
free(C);
return 0;
}
页:
[1]