Base conversion Integer Division +

A rectangular footprint

topic

We can use 2 small rectangle 1 of sideways or vertically to cover a larger rectangle. Will the use of n 2 small rectangle 1 coverage without overlap a large rectangle 2 * n, a total of how many ways?

Thinking

Fibonacci number

The number of binary 1

topic

It enters an integer (int), and outputs the binary number represents the number 1. Wherein a negative number indicates a complement.

Thinking

Negative complement, the preamble is a series of 1, int 32 bits

Code

class Solution {
public:
     int  NumberOf1(int n) {
         int cnt=0;
         if(n==0)
             cnt=0;
         else if(n>0){
             while(n>0){
                 if(n&1==1){
                     cnt++;
                 }
                 n /= 2;
             }
         }else{
             int div=0;
             while(n<0){
                 if(n&1==1){
                     cnt++;
                 }
                 n /= 2;
                 div++;
             }
             cnt += (32-div);
         }
         return cnt;
     }
};

Hexadecimal conversion

topic

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

Thinking

Obviously, this integer exceeds unsigned long long (20 decimal digits) represents a range requires handwritten Integer Division

Code

#include<iostream>
#include<stack>
#include<cstring>
#include<string>

using namespace std;

int num[30];
int tmp[30];
stack<int> bin;
string str;

bool equalZero(int num[]){
    bool flag=true;
    for(int i=0;i<=29;i++){
        if(num[i]!=0){
            flag=false;
            break;
        }
    }
    return flag;
}

int main(){
    while(cin>>str){
        //string存入int数组
        memset(num,0,sizeof(num));
        memset(tmp,0,sizeof(tmp));
        int len=str.size();
        int cnt=29;
        len--;
        while(len>=0){
            num[cnt--]=(str[len--]-'0');
        }
        //当num!=0时执行大数除法
        while(equalZero(num)==false){
            bin.push(num[29]%2);
            //大数除法
            int carry=0;
            for(int i=0;i<=29;i++){
                tmp[i]=(carry+num[i])/2;
                carry=(carry+num[i])%2;
                carry*=10;
            }
            memcpy(num,tmp,sizeof(tmp));
            memset(tmp,0,sizeof(tmp));
        }
        while(!bin.empty()){
            cout<<bin.top();
            bin.pop();
        }
        cout<<'\n';
    }
}

Guess you like

Origin www.cnblogs.com/cbw052/p/11755847.html