• Add Binary


    Given two binary strings, return their sum (also a binary string).

    For example,
    a = "11"
    b = "1"
    Return "100".

    起初尝试把2个二进制数转换成十进制在相加,得到和之后在转换为二进制,最后发现二进制数位数太长转换成十进制数会溢出。直接采用先对齐,然后每位相加的方法即可。

    public class Solution {
        
        public String addBinary(String a, String b) {
            String re = "";
            int size1 = a.length();
            int size2 = b.length();
            String longer = (a.length()>b.length())?a:b;
            String shorter = (b.length()<a.length())?b:a;
            int dis = Math.abs(size1-size2);
            //给短的补0以便和长的每位对齐
            for(int i=0;i<dis;i++){
                shorter = "0"+shorter;
            }
            int carry = 0;//进位逢二进一
            int size = longer.length();
            for(int j=size-1;j>=0;j--){
                int num1 = Integer.valueOf(longer.charAt(j)+"");
                int num2 = Integer.valueOf(shorter.charAt(j)+"");
                int sum = carry+num1+num2;//将每位以及低位的进位相加
                switch(sum){
                    case 0:
                        carry = 0;
                        re = "0"+re;
                        break;
                    case 1:
                        carry = 0;
                        re = "1"+re;
                        break;
                    case 2:
                        carry = 1;
                        re = "0"+re;
                        break;
                    case 3:
                        carry = 1;
                        re = "1"+re;
                        break;
                    default:break;
                }
            }
            //若进位为1表明最高位相加产生进位补1
            if(carry==1){
                re = "1"+re;
            }
            return re;
        }
    }
  • 相关阅读:
    Stream流之三级查询
    SpringBoot日期格式的设置
    el表达式
    SpringMV+HuTool之验证码登录
    Spring注解详解
    @ResponseBody注解使用(返回字符串并不跳转)
    每日leetcode-数组-589. N 叉树的前序遍历
    python apply函数
    剑指offer-JZ6 旋转数组的最小数字
    torch.manual_seed()函数
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4272691.html
Copyright © 2020-2023  润新知