Advertisement
IHATEMICROWAVEOVEN

trol

Nov 4th, 2024 (edited)
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. // 0 padding for the shorter binary string
  2. // (this step isn't necessary, but easier for noob solution)
  3. if(b.length()>a.length()){
  4. int temp = b.length()-a.length();
  5. for(int i=0; i<temp; i++){
  6. a = "0"+a;
  7. }
  8. }else if(b.length()<a.length()){
  9. int temp = a.length()-b.length();
  10. for(int i=0; i<temp; i++){
  11. b = "0"+b;
  12. }
  13. }
  14.  
  15.  
  16. // Initializing
  17. int curSum = 0;
  18. int carry = 0;
  19. String result = "";
  20.  
  21. // From the rightmost character to the leftmost
  22. for(int i=a.length()-1; i>=0; i--){
  23. curSum = (a.charAt(i)-48)+(b.charAt(i)-48)+carry;
  24. if(curSum==0){
  25. result = "0"+result;
  26. carry = 0;
  27. }else if(curSum==1){
  28. result = "1"+result;
  29. carry = 0;
  30. }else if(curSum==2){
  31. result = "0"+result;
  32. carry = 1;
  33. }else{
  34. result = "1"+result;
  35. carry = 1;
  36. }
  37. }
  38.  
  39. if(carry==1){
  40. return "1"+result;
  41. }
  42. return result;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement