两个非负整数A和B的十进制zip是整数C.

时间:2016-07-08 16:33:34

标签: c++ algorithm

The decimal zip of two non-negative integers A and B is an integer C whose 
 decimal representation is created from the decimal representations
 of A and B as follows:

• the first (i.e. the most significant) digit of C is the first digit of A;
• the second digit of C is the first digit of B;
• the third digit of C is the second digit of A;
• the fourth digit of C is the second digit of B;
• etc.

 If one of the integers A and B runs out of digits, the remaining digits of 
 the other integer are appended to the result.

 The decimal representation of 0 is assumed to be "0".

 For example, the decimal zip of 12 and 56 is 1526.
 The decimal zip of 56 and 12 is 5162.
 The decimal zip of 12345 and 678 is 16273845.
 The decimal zip of 123 and 67890 is 16273890.

 Write a function: function solution(A, B); that, given two non-negative
 integers A and B, returns their decimal zip.

 The function should return -1 if the result exceeds 100,000,000.

 For example, given A = 12345 and B = 678 the function should return 
 16273845, as explained above.

假设:

•A和B是[0..100,000,000]范围内的整数。

这是我的解决方案,但我得到了数组绑定的预期

所以我尝试将整数转换为字符串,以便我处理它,并将数字加在一起。

int solution(int A, int B) {
    // write your code in C++11 (g++ 4.8.2)
    if (A < 0 || A > 100000000) return -1;
    if (B < 0 || B > 100000000) return -1;

    string A_ = IntToString(A);
    string B_ = IntToString(B);
    string output = "";

    for (int i = 0; i < A_.size() || i < B_.size(); i++) {

        if (A_[i]) {
            output[i] = output[i] + A_[i];
        }

        if (B_[i]) {
            output[i] = output[i] + B_[i];
        }
    }

    return atoi(output.c_str());
}

7 个答案:

答案 0 :(得分:3)

Java解决方案

 public long calculateDecimalZip(long a, long b) {
    if ((a < 0 || a > 100000000) || ((b < 0 || b > 100000000))) {
        return -1;
    }
    char[] arrayFirstNumber = String.valueOf(a).toCharArray();
    char[] arraySecondNumber = String.valueOf(b).toCharArray();
    String aux = "";
    for (int i = 0; i < arrayFirstNumber.length || i < arraySecondNumber.length; i++) {
        if (i < arrayFirstNumber.length) {
            aux += arrayFirstNumber[i];
        }
        if (i < arraySecondNumber.length) {
            aux += arraySecondNumber[i];
        }
    }
    result = Long.parseLong(aux);
    if (result > 100000000) {
        return -1;
    }
    return result;

}

我希望对某人有所帮助。

答案 1 :(得分:1)

for循环仅在i达到最大字符串的大小时停止。但是,您继续使用i作为两个字符串的索引。因此,您将超出较短者的范围,从而导致错误。

而不是:

    if (A_[i])

你可能想要:

    if (i < A_.size())

答案 2 :(得分:1)

int solution(int A, int B) {
    char[] firstNumberChars = getChars(A);
    char[] secondNumberChars = getChars(B);

    int firstNumberLength = firstNumberChars.length;
    int secondNumberLength = secondNumberChars.length;
    int highestLength = Math.max(firstNumberLength, secondNumberLength);

    StringBuilder decimalZip = new StringBuilder();
    for (int i = 0; i < highestLength; i++) {
        if (i < firstNumberLength)
            decimalZip.append(firstNumberChars[i]);
        if (i < secondNumberLength)
            decimalZip.append(secondNumberChars[i]);
    }

    int maxValue = 100000000;
    int answer = Integer.parseInt(String.valueOf(decimalZip));
    if (answer > maxValue)
        return -1;
    return answer;
}

private static char[] getChars(int n) {
    return String.valueOf(n).toCharArray();
}

答案 3 :(得分:0)

您的算法逻辑错误。

您无法if (A_[i]) string i,并且output是有效索引时期望它为真。它将在无效索引上崩溃。

首先尝试以不同的方式重写逻辑(在纸上或在注释中),使用索引和字符串大小来查看在A或B中是否有下一个有效字符。

之后添加更长字符串的剩余部分(如果有的话)。

在使用output[i]之前,可能需要将

string output(A_.size()+B_.size(), '?');字符串设置为具有足够大的容量。与Private Sub UltraButtonSave_Click(sender As Object, e As EventArgs) Handles UltraButtonSave.Click If Not DBNull.Value.Equals(chkdtDataTable.Rows.Item(0).Item("ConveyanceID")) AndAlso Not DBNull.Value.Equals(chkdtDataTable.Rows.Item(0).Item("TripID")) Then Modal.ARG_ConveyanceID = chkdtDataTable.Rows.Item(0).Item("ConveyanceID") Modal.ARG_TripID = chkdtDataTable.Rows.Item(0).Item("TripID") Modal.ARG_NumberOfConveyance = UltraNumberOfConveyance.Value Dim prevDatevalue As Object = Nothing For Each o As Object In UltraPanel1.ClientArea.Controls If TypeOf (o) Is UltraDateTimeEditor Then Dim datePicker As UltraDateTimeEditor = o If prevDatevalue <> Nothing AndAlso datePicker.Value <> Nothing Then If datePicker.Value < prevDatevalue Then ' Do something Previous value is Lesser lblSuccess.Text = "Please verify date entered." lblSuccess.ForeColor = Color.Red Exit Sub End If End If Modal.ARG_CheckPointTimeID = Convert.ToInt32(datePicker.Tag.Split(","c)(0)) Modal.ARG_TerminalCheckPointID = Convert.ToInt32(datePicker.Tag.Split(","c)(1)) Modal.ARG_CheckPointTimeValue = datePicker.Value Helper.InsertCheckPointTimesScreen(Modal) Helper.GetCheckPointTimes(Modal) prevDatevalue = datePicker.Value lblSuccess.Text = "Data Saved Successfully." lblSuccess.ForeColor = Color.Green End If Next Else lblSuccess.Text = "Selected Order does not have Trip/Conveyance created." lblSuccess.ForeColor = Color.Red End If End Sub 一样。

强烈建议您学习如何使用调试器,这样您就可以在自己的眼睛中发现代码的所有意外行为,因此不必猜出您的错误。

请记住,计算机是非常严格的确定性机器,即。无论你告诉他们做什么,他们都会这样做。究竟。因此,在处理这样简单的源代码时,您可以拥有稳定的执行环境并且每次都重复该过程,很容易看到您真正编写的内容并使计算机执行,并将其与您的初始意图进行比较。

答案 4 :(得分:0)

在Javascript中

function solution(A, B) {
    if (A < 0 || A > 100000000) return -1;
    if (B < 0 || B > 100000000) return -1;

    A = A.toString();
    B = B.toString();

    var C = '';

    for(var i = 0; i < A.length || i < B.length; i++){
        if (A[i]) {
            C += A[i];
        }        
        if (B[i]) {
            C += B[i];
        }
    }

    return parseInt(C);    
}

答案 5 :(得分:0)

public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {

    public static final String API_KEY = "I HIDE MY API";  

    private String VIDEO_ID;  

    private AdView mAdView; 

    private Button skipbtn;

    private InterstitialAd mInterstitialAd;`


       `protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            //initializing Youtube Player View
            YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
            youTubePlayerView.initialize(API_KEY, this);
            MobileAds.initialize(this,
                    "ca-app-pub-3940256099942544~3347511713");

            //PUB
            mAdView = (AdView) findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            mAdView.loadAd(adRequest);
            mInterstitialAd = new InterstitialAd(this);
            mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
            mInterstitialAd.loadAd(new AdRequest.Builder().build());
            //FIN PUB

            mInterstitialAd.setAdListener(new AdListener() {
                @Override
                public void onAdClosed() {

                }
            });

            skipbtn = (Button) findViewById(R.id.skipbtn);
            skipbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                    }

                }
            });
        }



        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
            VIDEO_ID= new VIDEO_ID().getMes_Videos();
            youTubePlayer.setPlayerStateChangeListener(playerStateChangeListener);
            youTubePlayer.setPlaybackEventListener(playbackEventListener);
            if (!b)
                youTubePlayer.cueVideo(VIDEO_ID);
        }

        @Override
        public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
            Toast.makeText(this, "Failure to initialize", Toast.LENGTH_LONG).show();
        }

        private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {
            @Override
            public void onPlaying() {

            }

            @Override
            public void onPaused() {

            }

            @Override
            public void onStopped() {

            }

            @Override
            public void onBuffering(boolean b) {

            }

            @Override
            public void onSeekTo(int i) {

            }
        };

        private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {
            @Override
            public void onLoading() {

            }

            @Override
            public void onLoaded(String s) {

            }

            @Override
            public void onAdStarted() {

            }

            @Override
            public void onVideoStarted() {

            }

            @Override
            public void onVideoEnded() {

            }

            @Override
            public void onError(YouTubePlayer.ErrorReason errorReason) {

            }
        };
}

答案 6 :(得分:0)

使用stringstream将整数转换为字符串,并使用istringstream将字符串转换为整数。

#include <iostream>
#include <sstream>

using namespace std;

int solution(int A, int B) {
        // Validate inputs
        if (A < 0 || A > 100000000) return -1;
        if (B < 0 || B > 100000000) return -1;

        // Build string from integer A
        stringstream ssA;
        ssA << A;
        string sA(ssA.str());

        // Build string from integer B
        stringstream ssB;
        ssB << B;
        string sB(ssB.str());

        // Decimal zip string
        stringstream sZip;

        // Zip the two strings
        for(int x(0); x < sA.length() || x < sB.length(); ++x) {
                // x th eliement of A exists?
                if(sA[x])
                        sZip << sA[x];

                // x th eliement of B exists?
                if(sB[x])
                        sZip << sB[x];
        }

        // Create integer from string stream
        int num;
        istringstream(sZip.str()) >> num;

        // Return the decimal zip
        return num;
}