hd 1887 Weird Numbers

来源:互联网 发布:汇编语言转c语言 编辑:程序博客网 时间:2024/04/28 22:09
负进制的转换,用短除法.负进制r,当余数d<0时, d+r, 商s++;
#include <iostream>
#include 
<string>
#include 
<stack>
#include 
<vector>
#include 
<map>
using namespace std;
void change(int n, int r)
{
    
int y, s, t;
    stack
<int> st;
    
while (n)
    
{
        y 
= n % r;
        s 
= n / r;        
        
if(y < 0)
        
{
            y 
+= -r;
            s
++;
        }

        n 
= s;
        st.push(y);
    }

    
bool f = false;
    
while (!st.empty())
    
{
         t 
= st.top();
         st.pop();
         
if(t == 0 && !f)
             
continue;
         
else
         
{
             cout 
<< t;
             f 
= true;
         }

    }

    
if(!f)
        cout 
<< "0";
    cout 
<< endl;
}


int change2(string s, int r)
{
    
int i, sum = 0;
    
int t = 1;
    
for (i=s.size()-1; i>=0--i)
    
{
        sum 
+= (s[i]-'0')*t;
        t 
*= r;
    }

    
return sum;    
}

int main()
{
    
char c, c1;
    
int n, r;
    
string s;
    
while ( c = getchar())
    
{
        
if(c == 'e')
        
{
            getchar();
            getchar();
            
break;
        }

        
else if(c == 't')
        
{
            getchar();
            getchar();
            c 
= getchar();
            c1 
= getchar();
            
if(c1 == ' ')
            
{
                r 
= (c-'0');    
            }

            
else
            
{
                r 
= (c-'0')*10 + (c1-'0');
            }

            cin 
>> n;
            getchar();
            change(n, 
-r);
        }

        
else if(c == 'f')
        
{
            getchar();
            getchar();
            getchar();
            getchar();
            c 
= getchar();
            c1 
= getchar();
            
if(c1 == ' ')
            
{
                r 
= (c-'0');    
            }

            
else
            
{
                r 
= (c-'0')*10 + (c1-'0');
                getchar();
            }

            cin 
>> s;
            getchar();
            cout 
<< change2(s, -r) << endl;
        }

    }

    
return 0;
}

原创粉丝点击