OJ Question Record: Convert a decimal number to an octal number Question number: 545

Convert a decimal number to an octal numberSubject number: 545

Question requirement:
Convert three decimal numbers into octal numbers respectively, it is recommended to use stack to achieve.

Enter description
Enter three decimal numbers, each on a line.
Output description
Output the octal number corresponding to each decimal number, each occupying one line.
Input sample
256
189
15
Output sample
400
275
17

Problem-solving idea: When
a decimal integer is converted to an octal number, it can be done by dividing by 8. When converting from high to low, the remainder obtained first is the low digit, and we need to convert from high to low, so we push the obtained remainder into the stack in turn, because the stack is first in and out, and it can be realized when output The result output from high order to low order.

Customs clearance code:

#include <iostream> 

#define LENGTH 10

using namespace std;

class Stack {
    
    
	public:
		Stack():top_(-1) {
    
    }
		
	public:
		void Push(int val);
		void Pop();
		void Print();
		
	private:
		int list_[LENGTH];
		int top_;
};

void Stack::Push(int val) {
    
    
	top_++;
	list_[top_] = val;
}

void Stack::Pop() {
    
    
	top_--;
}

void Stack::Print() {
    
    
	while (top_ != -1) {
    
    
		cout << list_[top_];
		top_--;
	}
	cout << endl;
}

void printOctal(int decimal) {
    
    
	Stack res;
	
	while (decimal != 0) {
    
    
		res.Push(decimal % 8);
		decimal = decimal / 8;
	}
	
	res.Print();
}

int main() {
    
    
	int a, b, c;
	
	cin >> a >> b >> c;
	
	printOctal(a);
	printOctal(b);
	printOctal(c);
	
	return 0;
}

complete.

Guess you like

Origin blog.csdn.net/weixin_45711556/article/details/108689452