Advertisement
UniQuet0p1

Untitled

Jan 29th, 2022
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. package intro;
  2.  
  3. public class Program {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int decimal = asDecimal("11001101");
  8.  
  9. System.out.println(decimal); // 205
  10. System.out.println(asString(205)); //205
  11. }
  12.  
  13. public static String asString(int input) {
  14. String result = "";
  15. while (input > 0) {
  16. if (input % 2 == 0) {
  17. result = '0' + result;
  18. } else {
  19. result = '1' + result;
  20. }
  21. }
  22.  
  23. return result;
  24. }
  25.  
  26. public static int asDecimal(String input) {
  27. input = reverse(input);
  28.  
  29. int result = 0;
  30. for (int i = 0; i < input.length(); i++) {
  31. if (input.charAt(i) == '1') {
  32. result += pow(2, i);
  33. }
  34. }
  35. return result;
  36. }
  37.  
  38. private static String reverse(String input) {
  39. String result = "";
  40. for (int i = 0; i < input.length(); i++){
  41. result = input.charAt(i) + result;
  42. }
  43. return result;
  44. }
  45.  
  46. private static int pow(int arg, int power) {
  47. if (arg == 0){
  48. return 1;
  49. }
  50. int result = 1;
  51. for (int i = 0; i < power; i++) {
  52. result *= arg;
  53. }
  54.  
  55. return result;
  56. }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement