LeetCode第二題 C解答
阿新 • • 發佈:2019-01-08
/**
計算兩數的和
*/
int add(struct ListNode* l1, struct ListNode*l2){
float v1=0, v2=0;
int c1=0, c2=0;
do{
v1=v1 + l1->val*pow(10,c1);
l1=l1->next;
c1++;
}while(l1 != NULL);
do{
v2=v2 + l2->val*pow(10,c2);
l2=l2->next;
c2++;
}while(l2 != NULL);
return (int)v1 + (int)v2;
}
/*
把和數反轉
*/
int backInt(int *in){
int i;
int v=*in;
*in=0;
if(v%10)
{
while(v>0)
{
*in=(*in)*10+v%10;
v=v/10;
}
}
else
{
while(v>0)
{
*in=(*in)*10+v%10;
v=v/10;
printf("1n%d",*in);
}
*in=10*(*in);
}
return *in;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int v,v0;
int v3=add(l1, l2);
printf("v3%d",v3);
v= backInt(&v3);
v0=v;
if(v%10==0)
{
v/=10;
}
struct ListNode *p, *node;
p=(struct ListNode*)malloc(sizeof(struct ListNode));
p->val=v%10;
p->next=NULL;
printf("p%d",p->val);
v=v/10;
while(v>0){
node=(struct ListNode*)malloc(sizeof(struct ListNode));
node->val=v%10;
v=v/10;
node->next=p;
p=node;
node=NULL;
}
if(!(v0%10)&&(v0!=0))
{
node=(struct ListNode*)malloc(sizeof(struct ListNode));
node->val=0;
node->next=p;
p=node;
node=NULL;
}
return p;
}
計算兩數的和
*/
int add(struct ListNode* l1, struct ListNode*l2){
float v1=0, v2=0;
int c1=0, c2=0;
do{
v1=v1 + l1->val*pow(10,c1);
l1=l1->next;
c1++;
}while(l1 != NULL);
do{
v2=v2 + l2->val*pow(10,c2);
l2=l2->next;
c2++;
}while(l2 != NULL);
return (int)v1 + (int)v2;
}
/*
把和數反轉
*/
int backInt(int *in){
int i;
int v=*in;
*in=0;
if(v%10)
{
while(v>0)
{
*in=(*in)*10+v%10;
v=v/10;
}
}
else
{
while(v>0)
{
*in=(*in)*10+v%10;
v=v/10;
printf("1n%d",*in);
}
*in=10*(*in);
}
return *in;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int v,v0;
int v3=add(l1, l2);
printf("v3%d",v3);
v= backInt(&v3);
v0=v;
if(v%10==0)
{
v/=10;
}
struct ListNode *p, *node;
p=(struct ListNode*)malloc(sizeof(struct ListNode));
p->val=v%10;
p->next=NULL;
printf("p%d",p->val);
v=v/10;
while(v>0){
node=(struct ListNode*)malloc(sizeof(struct ListNode));
node->val=v%10;
v=v/10;
node->next=p;
p=node;
node=NULL;
}
if(!(v0%10)&&(v0!=0))
{
node=(struct ListNode*)malloc(sizeof(struct ListNode));
node->val=0;
node->next=p;
p=node;
node=NULL;
}
return p;
}