给一个十进制数转换为二进制,考虑之前取十进制数每位的权值,如下
import java.util.Scanner;
import java.util.Stack;
public class Transformation {
Stack<Integer> s;
void ten(int num) {
s = new Stack<Integer>();
while(num != 0){
s.push(num % 10);
num /= 10;
}
while (!s.empty()) System.out.print(s.pop());
}
public static void main(String []args) {
Transformation t = new Transformation();
Scanner input = new Scanner(System.in);
int temp = input.nextInt();
t.ten(temp);
}
}
当然,若不想使用栈可以采用递归,如下
import java.util.Scanner;
public class Transformation {
void ten(int num) {
int res = num % 10;
if ((num/10) == 0) {
System.out.print(num);
return ;
}else ten(num/10);
System.out.print(res);
return ;
}
public static void main(String []args) {
Transformation t = new Transformation();
Scanner input = new Scanner(System.in);
int temp = input.nextInt();
t.ten(temp);
}
}
同理,若每次除2取余2得到的就是2进制每位的权值,故代码如下
import java.util.Scanner;
public class Transformation {
void ten(int num) {
int res = num % 2;
if ((num/2) == 0) {
System.out.print(num);
return ;
}else ten(num/2);
System.out.print(res);
return ;
}
public static void main(String []args) {
Transformation t = new Transformation();
Scanner input = new Scanner(System.in);
int temp = input.nextInt();
t.ten(temp);
}
}