2012-11-14 3 views
1

2 진수를 파싱하지 않고 2 진수 (2 진수 만)를 빼는 이진 계산기를 만들려고합니다.Java에서 이진 빼기

누구든지 내가 위쪽 숫자에 0을, 낮은 숫자에 하나를 두는 상황에 도움이 될 수 있습니까? 코드를 작성할 수없는 것 같습니다.

for (int i = ss.length()-1; i > -1; i--) 
     { 
      if(s.charAt(i)=='0' && ss.charAt(i)=='0') sb.append("0"); 
      else if (s.charAt(i)=='1' && ss.charAt(i)=='0') sb.append("1"); 
      else if (s.charAt(i)=='1' && ss.charAt(i)=='1') sb.append("0"); 
      else 
      { 
       sb.append("1"); 
       doit(s,i+1,sb); 
      } 
     } 

     for (int i = s.length() - ss.length(); i >-1; i--) 
     { 
      sb.append(s.charAt(i)); 
     } 

     ArrayList<Character> res = new ArrayList<>(); 
     for (int i = sb.length()-1; i > -1; i--) 
     { 
      res.add(sb.charAt(i)); 
     } 
     System.out.println(res); 
    } 
    public static void doit(StringBuilder s, int i, StringBuilder sb) 
    { 
     for (int j = i; j > -1; j--) 
     { 
      if(s.charAt(j)=='0') 
      { 
       s.setCharAt(j, '1'); 
      } 
      else 
      { 
       s.setCharAt(j, '0'); 
       break; 
      } 
     } 
    } 
+2

시도한 코드 중 일부를 표시 할 수 있습니까? 그리고 당신은 무엇을 의미합니까? - '2 진수 (2 진수 만)'? 이진수는 기본 2 만 맞습니까? 왜 명시 적 언급인가? –

+2

[무엇을 시도해 봤습니까?] (http://whathaveyoutried.com) –

+1

'파싱하지 않고 '정의 할 수 있습니까? 두 개의 숫자를 빼도록 말할 수는 없지만 읽을 수있는 권한은 부여하지 않습니다. – jlordo

답변

0

적어도 일부 칩처럼 오른쪽에서 왼쪽으로 엄격하게 지정할 수 있습니다. 까다로운 지식은 5 열로 구성된 테이블입니다 : (a, b, 이전 위치의 캐리 비트) -> (결과, 새로운 캐리 비트). 너는 더 높은 위치에서 실제로 빌려 가지 않는다; 당신은 그 대신에 underverflow를 가지고 간다.

http://books.google.com.ua/books?id=vpWS-s4d5vMC&pg=PA25&lpg=PA25&dq=binary+subtraction+table+carry&source=bl&ots=458JWgZl8v&sig=sjuXedv96KCbNWmxQAPNQo7iuRw&hl=en&sa=X&ei=i-6jUI7IB8jusgay8IDQDQ&ved=0CBwQ6AEwAA#v=onepage&q=binary%20subtraction%20table%20carrysubtract&f=false

이 두 가지 방법을 정의한다 : 여기서 표 2.4 참조 (A, B, 이전 위치로부터 조금 전달) -> 결과 및 (A, B, 이전 위치에서 비트를 전달) -> 새로운 캐리 비트 오른쪽에서 왼쪽으로 적용하십시오.


대안 : 여기에 규칙에 따라 두 번째 인수를 반전 : http://simple.wikipedia.org/wiki/Negative_binary_numbers.

다음 역 # 2 :)에 # 1을 추가하십시오.

추신. 누가 나쁜 임무라고 했지 :)?

2

이진 규칙.

1 - 1 = 0 
0 - 0 = 0 
1 - 0 = 1 
0 - 1 = 1 (needs a carry bit from a higher bit position. 
    You might have to check several higher bits before you 
    find the carry bit. -1 otherwise.) 
+0

코드를 추가 할 수 있습니다. 왜이 기능이 작동하지 않는지 말할 수 있습니까? –

+0

찾기 힘들다 : 절차가 너무 복잡하다. 디버깅/nitpicking 필요합니다. 좀 더 구조화 된 접근법을 사용하여 다시 해보는 것이 좋습니다. 내 대답을 보라. 바로 오른쪽에서 왼쪽으로 이동하십시오. 각 단계에서 (a, b, carry)를 a-b 및 new carry로 각각 매핑하는 두 가지 간단한 메소드를 사용하십시오. 메서드는 쓰기 쉽습니다 : (a, b, carry)의 8 가지 조합 각각에 대해 출력 비트를 반환합니다. 그리고 당신의 코드는 마술처럼 분명해질 것이며, 기회는 바로있을 것입니다. 아니면 쉽게 디버깅 할 수 있습니다. 시도 해봐! –

-1
import java.util.Scanner; 
class binary_diff 
{ 
    public String diff(String st1,String st2) 
    { 
     String nst="",max="";char b='0';boolean tf=(st1.length()>=st2.length()); 
     int l1=st1.length(),l2=st2.length(); 
     if(l1<l2) 
     for(int a=1;a<=l2-l1;a++) 
     st1='0'+st1; 

     else if(l2<l1) 
     for(int a=1;a<=l1-l2;a++) 
     st2="0"+st2; 
     if(!tf)for(int a=l1-1;a>=0;a--) 
     if(st1.charAt(a)!=st2.charAt(a)) 
     if(st2.charAt(a)=='1'){max=st2;st2=st1;st1=max;break;} 

     for(int a=st1.length()-1;a>=0;a--) 
     { 
      if(st1.charAt(a)=='1' && st2.charAt(a)=='0') 
      { 
       if(b=='1') 
       {nst='0'+nst;b='0';} 
       else 
       nst='1'+nst; 
      } 

      else if(st1.charAt(a)==st2.charAt(a) && st2.charAt(a)=='1') 
      { 
       if(b=='1') 
       {nst='1'+nst;b='1';} 
       else 
       nst='0'+nst; 
      } 

      else if(st1.charAt(a)=='0' && st2.charAt(a)=='1') 
      { 
       if(b=='1') 
       nst='0'+nst; 
       else 
       {nst='1'+nst;b='1';} 
      } 

      else 
      { 
       if(b=='1') 
       nst='1'+nst; 
       else 
       nst='0'+nst; 
      } 
     } 
     return nst; 
    } 

    public static void main() 
    { 
     Scanner sc=new Scanner(System.in); 
     System.out.println("Enter the two numbers"); 
     String s1=sc.next(); 
     String s2=sc.next(); 
     binary_diff bd=new binary_diff(); 
    System.out.println(bd.diff(s1,s2)); 
    } 
}