C++ code


  • 0

    //think ; 12389->12421 11211->11111 11011->11111 10000->9999 10->9 11 ->9

     class Solution {
     public:
      long long s2int(string s)
     {
        long long x=0;
        for(int i=0;i<s.size();i++)
        {
            x=x*10+int(s[i]-'0');
        }
        return x;
    }
    
    
    long long mind;
    string ans;
      
     void updata(string x,string n)
     {
          long long cur=s2int(x)-s2int(n);
          if(cur==0)
          return ;
          if(cur<0)cur=-cur;
          if(cur<=mind)
            {
                 if(cur==mind)
                 {
                     if(s2int(x)<s2int(ans))
                            ans=x;
                 }
                 else 
                 {
                    ans=x;
                    mind=cur;
                 }
             }
     }
    
    
    string nearestPalindromic(string n) 
    {
     
     int len=n.size();
    if(len==1)
     {
         return to_string(s2int(n)-1);
     }
    
        mind=1000000000;
        ans="9";
      
      string x=n;
      
         for(int i=0;i<len/2-1;i++)             //最前面的不变
         {
             if(n[i]!=n[len-i-1])
             {
                 x[len-i-1]=x[i];
             }
         }
         
      
          
         for(int i=0;i<10;i++)
         {
             if(len%2==0)
             {
             x[len/2]=char('0'+i);
             x[len/2-1]=char('0'+i);
             }
             else
             {
                   x[len/2+1]=char('0'+i);
                   x[len/2-1]=char('0'+i);
                   
                   
                           string tx=x;             //奇数情况,中间值改变+/-1
                           if(x[len/2]>'0')
                            tx[len/2]=char(x[len/2]-1);
                             updata(tx,n);
                           
                            tx[len/2]=char(x[len/2]+1);
                            updata(tx,n);
                   
             }
             
             updata(x,n);
         }
         
         string ts,ts1="1";
         
         for(int i=0;i<18;i++)    //可能是9999..9 或者10..001
        {
            ts+='9';
            updata(ts,n);
            ts1+='0';
            updata(ts1+"1",n);
        }  
     
        return ans;
    }
    

    };


Log in to reply
 

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