I want to know whether my programing's foramt correct or not? Thank you, Hope you can get my idea.


  • 0
    C

    #include<stdio.h>
    #include<stdlib.h>

    typedef struct myhappy
    {
    int val;
    struct myhappy *next;
    }HPN;

    HPN *DivateNum(int );
    void InSertH2(HPN *,int);
    int Check(HPN *, int);
    void DeletH1(HPN *);

    void DeletH1(HPN *HH1)
    {
    HPN *q,*p;
    p=HH1->next;
    while(p!=NULL)
    {
    q=p;
    p=p->next;
    free(q);
    }
    }

    int Check(HPN *H2,int n)
    {
    int i,ju=1,cn=0;
    HPN *p;
    p=H2->next;
    while(p!=NULL&&ju)
    {
    if(p->val!=n)
    p=p->next;
    else if(p->val==n)
    {
    ju=0;
    cn=1;//it means it has appeared cycle
    }
    }
    return cn;
    }

    void InSertH2(HPN *HH,int n)
    {
    HPN *p,*q;
    p=HH->next;
    while(p->next!=NULL)
    p=p->next;
    q=(HPN *)malloc(sizeof(HPN));
    q->val=n;
    p->next=q;
    p=q;
    p->next=NULL;
    }

    HPN *DivateNum(int num)
    {
    HPN *H1,*p1,q1;
    int a,b;
    int ju=1;
    H1=(HPN
    )malloc(sizeof(HPN));
    H1->next=NULL;
    p1=H1;
    b=num;
    while(ju==1)
    {

    	 if((b/10)!=0)
    	 {
    	      ju=1;			 
    		  a=b%10;
    	      q1=(HPN*)malloc(sizeof(HPN));
    	      q1->val=a;
    	      p1->next=q1;
    	      p1=q1;
    		  b=b/10;
    	 }
    	 else 
    	 {
    		 ju=0;
    		 q1=(HPN*)malloc(sizeof(HPN));
    	     q1->val=b;
    	     p1->next=q1;
    	     p1=q1;	 
    	 } 	     
     } 
     p1->next=NULL;
     return H1;
    

    }
    int main()
    {
    int i;
    int num;
    int cnum=0;
    int n,ju=1,ju2=0;
    int a,b;
    HPN *H1,*H2,*p1,p2,q1,q2;
    H1=(HPN
    )malloc(sizeof(HPN));
    H1->next=NULL;
    p1=H1;
    H2=(HPN
    )malloc(sizeof(HPN));
    H2->next=NULL;
    p2=H2;
    printf("please input a number:");
    scanf("%d",&num);
    getchar();
    q2=(HPN )malloc(sizeof(HPN));
    q2->val=num;
    p2->next=q2;
    p2=q2;
    p2->next=NULL;
    cnum=num;
    if(num==1)
    printf("%d is happy number",num);
    else
    {
    while(ju==1)
    {
    H1=(HPN
    )malloc(sizeof(HPN));
    H1->next=NULL;
    H1=DivateNum(cnum);//recount the number
    p1=H1->next;
    cnum=0;//set cnum to 0,join the compute
    while(p1!=NULL)
    {
    cnum=cnum+(p1->val)
    (p1->val);
    printf("%d^2",p1->val);
    p1=p1->next;
    if(p1!=NULL)
    printf("+");

    	 }
    	 printf("=%d\n",cnum);
    	 ju2=Check(H2,cnum);//judgement whether appear cycle 
    	 if(ju2==0)
    	 {
    	     InSertH2(H2,cnum);	
    		 DeletH1(H1);//delete linklist H1,storage each digit
    	 }
    	 else 
    	 {
    	     ju=0;
    		 printf("%d is not HAPPY NUMBER\n",num);
    	 }		 
    	if(cnum==1)
    	 {
    	    ju=0;
    		printf("%d is HAPPY NUMBER\n",num);
    	 }
       }
     
     }
    
     getchar();
         return 0;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.