Base conversion - cattle-off

Title Description

A length of up to 30 decimal digits nonnegative integer output is converted into a binary number.

Enter a description:

A plurality of sets of data, each of the behavior of a length of not more than 30 decimal nonnegative integer. 
(Note that the number is a decimal number 30 may have, instead of the integer 30bits)

Output Description:

Binary number corresponding to each line of output.
Example 1

Entry

0
1
3
8

Export

0
1
11
1000

Problem-solving ideas

This is a process on large numbers of integers, the length of an integer of 30, we use a string is stored.

First, we recall, the decimal number into a binary number when the approach adopted is  "In addition modulo 2, in reverse order"  approach:

 

 Then it is clear that we need an array to hold the remainder, or you can use a stack implementation in reverse order;

 The problem can be transformed into large numbers in addition to how to find the remainder 2. For a number, the remainder of which depends only on its two last bit, i.e., the remainder of which the last one is 2;

 So we have to store every time divided by 2, and whichever be the last one to take over.

 Finally, the remainder can be output in reverse order, Also note that the number of every character are processed. 


 1 #include <iostream>
 2 #include <string>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     char s[31];
 9     while(cin>>s)
10     {
11         int carry = 0; //进位位;
12         int index  = 0;
13         int zero_num = 0;
14         char t[10000];
15         int len = strlen(s);
16 
17         while(1)
18         {
19             zero_num=0;
20             t[index++] = (s[len-1]-'0')%2 + '0';
21             for(int i=0;i<len;i++)
22             {
23                 carry = (s[i]-'0')%2;    // accordance decimal vertical division, starting with high except from 
24                  S [I] = (S [I] - ' 0 ' ) / 2 + ' 0 ' ;   // save high vertical division quotient i.e. above figures 
25                  S [I + . 1 ] = with Carry * 10 + S [I + . 1 ];
 26 is                  IF (S [I] == ' 0 ' ) zero_num ++ ;
 27              }
 28              IF (zero_num == len) BREAK ;
 29          }
 30          for ( int I = index-1;i>=0;i--)
31         {
32             cout << t[i];
33         }
34         cout << endl;
35     }
36 }

 

Guess you like

Origin www.cnblogs.com/jiashun/p/newcode21.html